home *** CD-ROM | disk | FTP | other *** search
/ Linux Cubed Series 2: Applications / Linux Cubed Series 2 - Applications.iso / editors / emacs / xemacs / xemacs-1.004 / xemacs-1 / xemacs-19.13 / src / fileio.c < prev    next >
Encoding:
C/C++ Source or Header  |  1995-08-28  |  123.6 KB  |  4,316 lines

  1. /* File IO for XEmacs.
  2.    Copyright (C) 1985-1988, 1992-1994 Free Software Foundation, Inc.
  3.  
  4. This file is part of XEmacs.
  5.  
  6. XEmacs is free software; you can redistribute it and/or modify it
  7. under the terms of the GNU General Public License as published by the
  8. Free Software Foundation; either version 2, or (at your option) any
  9. later version.
  10.  
  11. XEmacs is distributed in the hope that it will be useful, but WITHOUT
  12. ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13. FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14. for more details.
  15.  
  16. You should have received a copy of the GNU General Public License
  17. along with XEmacs; see the file COPYING.  If not, write to the Free
  18. Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */
  19.  
  20. /* Synched up with: Mule 2.0, FSF 19.28. */
  21.  
  22. #include <config.h>
  23. #include "lisp.h"
  24.  
  25. #include "buffer.h"
  26. #include "events.h"
  27. #include "frame.h"
  28. #include "insdel.h"
  29. #include "lstream.h"
  30. #include "mule.h"
  31. #include "redisplay.h"
  32. #include "sysdep.h"
  33. #include "window.h"             /* minibuf_level */
  34.  
  35. #include "sysfile.h"
  36. #include "sysproc.h"
  37. #include "syspwd.h"
  38. #include "systime.h"
  39. #include "sysdir.h"
  40.  
  41. #ifdef HPUX
  42. #include <netio.h>
  43. #ifdef HPUX_PRE_8_0
  44. #include <errnet.h>
  45. #endif
  46. #endif
  47.  
  48. /* Nonzero during writing of auto-save files */
  49. static int auto_saving;
  50.  
  51. /* Set by auto_save_1 to mode of original file so Fwrite_region_internal
  52.    will create a new file with the same mode as the original */
  53. static int auto_save_mode_bits;
  54.  
  55. /* Alist of elements (REGEXP . HANDLER) for file names 
  56.    whose I/O is done with a special handler.  */
  57. Lisp_Object Vfile_name_handler_alist;
  58.  
  59. /* Functions to be called to process text properties in inserted file.  */
  60. Lisp_Object Vafter_insert_file_functions;
  61.  
  62. /* Functions to be called to create text property annotations for file.  */
  63. Lisp_Object Vwrite_region_annotate_functions;
  64.  
  65. /* During build_annotations, each time an annotation function is called,
  66.    this holds the annotations made by the previous functions.  */
  67. Lisp_Object Vwrite_region_annotations_so_far;
  68.  
  69. /* File name in which we write a list of all our auto save files.  */
  70. Lisp_Object Vauto_save_list_file_name;
  71.  
  72. /* On VMS, nonzero means write new files with record format stmlf.
  73.    Zero means use var format.  */
  74. int vms_stmlf_recfm;
  75.  
  76. Lisp_Object Qfile_name_handler_alist;
  77.  
  78. /* These variables describe handlers that have "already" had a chance
  79.    to handle the current operation.
  80.  
  81.    Vinhibit_file_name_handlers is a list of file name handlers.
  82.    Vinhibit_file_name_operation is the operation being handled.
  83.    If we try to handle that operation, we ignore those handlers.  */
  84.  
  85. static Lisp_Object Vinhibit_file_name_handlers;
  86. static Lisp_Object Vinhibit_file_name_operation;
  87.  
  88. Lisp_Object Qfile_error, Qfile_already_exists;
  89.  
  90. Lisp_Object Qauto_save_hook;
  91. Lisp_Object Qauto_save_error;
  92. Lisp_Object Qauto_saving;
  93.  
  94. Lisp_Object Qcar_less_than_car;
  95.  
  96. /* Mask of bits indicating the descriptors that we wait for input on */
  97. extern SELECT_TYPE input_wait_mask, process_only_mask, device_only_mask;
  98.  
  99. /* signal a file error when errno contains a meaningful value. */
  100.  
  101. DOESNT_RETURN
  102. report_file_error (CONST char *string, Lisp_Object data)
  103. {
  104.   Lisp_Object errstring = build_string (strerror (errno));
  105.  
  106.   /* System error messages are capitalized.  Downcase the initial
  107.      unless it is followed by a slash.  */
  108.   if (string_char (XSTRING (errstring), 1) != '/')
  109.     set_string_char (XSTRING (errstring), 0,
  110.              DOWNCASE (current_buffer,
  111.                    string_char (XSTRING (errstring), 0)));
  112.  
  113.   signal_error (Qfile_error,
  114.                 Fcons (build_translated_string (string),
  115.                Fcons (errstring, data)));
  116. }
  117.  
  118. /* signal a file error when errno does not contain a meaningful value. */
  119.  
  120. DOESNT_RETURN
  121. signal_file_error (CONST char *string, Lisp_Object data)
  122. {
  123.   signal_error (Qfile_error,
  124.                 list2 (build_translated_string (string), data));
  125. }
  126.  
  127. DOESNT_RETURN
  128. signal_double_file_error (CONST char *string1, CONST char *string2,
  129.               Lisp_Object data)
  130. {
  131.   signal_error (Qfile_error,
  132.                 list3 (build_translated_string (string1),
  133.                build_translated_string (string2),
  134.                data));
  135. }
  136.  
  137. DOESNT_RETURN
  138. signal_double_file_error_2 (CONST char *string1, CONST char *string2,
  139.                 Lisp_Object data1, Lisp_Object data2)
  140. {
  141.   signal_error (Qfile_error,
  142.                 list4 (build_translated_string (string1), 
  143.                build_translated_string (string2),
  144.                data1, data2));
  145. }
  146.  
  147. static Lisp_Object
  148. close_file_unwind (Lisp_Object fd)
  149. {
  150.   if (CONSP (fd))
  151.     {
  152.       if (INTP (XCAR (fd)))
  153.     close (XINT (XCAR (fd)));
  154.  
  155.       free_cons (XCONS (fd));
  156.     }
  157.   else
  158.     close (XINT (fd));
  159.  
  160.   return Qnil;
  161. }
  162.  
  163. /* Restore point, having saved it as a marker.  */
  164.  
  165. static Lisp_Object
  166. restore_point_unwind (Lisp_Object point_marker)
  167. {
  168.   BUF_SET_PT (current_buffer, marker_position (point_marker));
  169.   return (Fset_marker (point_marker, Qnil, Qnil));
  170. }
  171.  
  172. /* Versions of read() and write() that allow quitting out of the actual
  173.    I/O.  We don't use immediate_quit (i.e. direct longjmp() out of the
  174.    signal handler) because that's way too losing.
  175.  
  176.    (#### Actually, longjmp()ing out of the signal handler may not be
  177.    as losing as I thought.  See sys_do_signal() in sysdep.c.)
  178.  
  179.    Solaris include files declare the return value as ssize_t.
  180.    Is that standard? */
  181. int
  182. read_allowing_quit (int fildes, void *buf, unsigned int nbyte)
  183. {
  184.   int nread;
  185.   QUIT;
  186.  
  187.   nread = sys_read_1 (fildes, buf, nbyte, 1);
  188.   return nread;
  189. }
  190.  
  191. int
  192. write_allowing_quit (int fildes, CONST void *buf, unsigned int nbyte)
  193. {
  194.   int nread;
  195.  
  196.   QUIT;
  197.   nread = sys_write_1 (fildes, buf, nbyte, 1);
  198.   return nread;
  199. }
  200.  
  201.  
  202. Lisp_Object Qexpand_file_name;
  203. Lisp_Object Qfile_truename;
  204. Lisp_Object Qsubstitute_in_file_name;
  205. Lisp_Object Qdirectory_file_name;
  206. Lisp_Object Qfile_name_directory;
  207. Lisp_Object Qfile_name_nondirectory;
  208. Lisp_Object Qunhandled_file_name_directory;
  209. Lisp_Object Qfile_name_as_directory;
  210. Lisp_Object Qcopy_file;
  211. Lisp_Object Qmake_directory_internal;
  212. Lisp_Object Qdelete_directory;
  213. Lisp_Object Qdelete_file;
  214. Lisp_Object Qrename_file;
  215. Lisp_Object Qadd_name_to_file;
  216. Lisp_Object Qmake_symbolic_link;
  217. Lisp_Object Qfile_exists_p;
  218. Lisp_Object Qfile_executable_p;
  219. Lisp_Object Qfile_readable_p;
  220. Lisp_Object Qfile_symlink_p;
  221. Lisp_Object Qfile_writable_p;
  222. Lisp_Object Qfile_directory_p;
  223. Lisp_Object Qfile_accessible_directory_p;
  224. Lisp_Object Qfile_modes;
  225. Lisp_Object Qset_file_modes;
  226. Lisp_Object Qfile_newer_than_file_p;
  227. Lisp_Object Qinsert_file_contents;
  228. Lisp_Object Qwrite_region;
  229. Lisp_Object Qverify_visited_file_modtime;
  230. Lisp_Object Qset_visited_file_modtime;
  231. Lisp_Object Qset_buffer_modtime;
  232.  
  233. /* If FILENAME is handled specially on account of its syntax,
  234.    return its handler function.  Otherwise, return nil.  */
  235.  
  236. DEFUN ("find-file-name-handler", 
  237.        Ffind_file_name_handler, Sfind_file_name_handler, 1, 2, 0,
  238.     "Return FILENAME's handler function for OPERATION, if it has one.\n\
  239. Otherwise, return nil.\n\
  240. A file name is handled if one of the regular expressions in\n\
  241. `file-name-handler-alist' matches it.\n\n\
  242. If OPERATION equals `inhibit-file-name-operation', then we ignore\n\
  243. any handlers that are members of `inhibit-file-name-handlers',\n\
  244. but we still do run any other handlers.  This lets handlers\n\
  245. use the standard functions without calling themselves recursively.")
  246.    (filename, operation)
  247.   Lisp_Object filename, operation;
  248. {
  249.   /* This function must not munge the match data.  */
  250.   Lisp_Object chain, inhibited_handlers;
  251.  
  252.   CHECK_STRING (filename, 0);
  253.  
  254.   if (EQ (operation, Vinhibit_file_name_operation))
  255.     inhibited_handlers = Vinhibit_file_name_handlers;
  256.   else
  257.     inhibited_handlers = Qnil;
  258.  
  259.   for (chain = Vfile_name_handler_alist; CONSP (chain);
  260.        chain = XCDR (chain))
  261.     {
  262.       Lisp_Object elt = XCAR (chain);
  263.       if (CONSP (elt))
  264.     {
  265.       Lisp_Object string;
  266.       string = XCAR (elt);
  267.       if (STRINGP (string)
  268.           && (fast_string_match (string, 0, filename, 0, -1, 0, 0) >= 0))
  269.         {
  270.           Lisp_Object handler = XCDR (elt);
  271.           if (NILP (Fmemq (handler, inhibited_handlers)))
  272.         return (handler);
  273.         }
  274.     }
  275.       QUIT;
  276.     }
  277.   return Qnil;
  278. }
  279.  
  280. static Lisp_Object
  281. call2_check_string (Lisp_Object fn, Lisp_Object arg0, Lisp_Object arg1)
  282. {
  283.   /* This function can GC */
  284.   Lisp_Object result = call2 (fn, arg0, arg1);
  285.   CHECK_STRING (result, 0);
  286.   return (result);
  287. }
  288.  
  289. static Lisp_Object
  290. call3_check_string (Lisp_Object fn, Lisp_Object arg0, 
  291.                     Lisp_Object arg1, Lisp_Object arg2)
  292. {
  293.   /* This function can GC */
  294.   Lisp_Object result = call3 (fn, arg0, arg1, arg2);
  295.   CHECK_STRING (result, 0);
  296.   return (result);
  297. }
  298.  
  299.  
  300. DEFUN ("file-name-directory", Ffile_name_directory, Sfile_name_directory,
  301.   1, 1, 0,
  302.   "Return the directory component in file name NAME.\n\
  303. Return nil if NAME does not include a directory.\n\
  304. Otherwise return a directory spec.\n\
  305. Given a Unix syntax file name, returns a string ending in slash;\n\
  306. on VMS, perhaps instead a string ending in `:', `]' or `>'.")
  307.   (file)
  308.      Lisp_Object file;
  309. {
  310.   /* This function can GC */
  311.   Bufbyte *beg;
  312.   Bufbyte *p;
  313.   Lisp_Object handler;
  314.  
  315.   CHECK_STRING (file, 0);
  316.  
  317.   /* If the file name has special constructs in it,
  318.      call the corresponding file handler.  */
  319.   handler = Ffind_file_name_handler (file, Qfile_name_directory);
  320.   if (!NILP (handler))
  321.     {
  322.       Lisp_Object retval = call2 (handler, Qfile_name_directory,
  323.                   file);
  324.  
  325.       if (!NILP (retval))
  326.     CHECK_STRING (retval, 0);
  327.       return retval;
  328.     }
  329.  
  330. #ifdef FILE_SYSTEM_CASE
  331.   file = FILE_SYSTEM_CASE (file);
  332. #endif
  333.   beg = string_data (XSTRING (file));
  334.   p = beg + string_length (XSTRING (file));
  335.  
  336.   while (p != beg && p[-1] != '/'
  337. #ifdef VMS
  338.      && p[-1] != ':' && p[-1] != ']' && p[-1] != '>'
  339. #endif /* VMS */
  340. #ifdef MSDOS
  341.      && p[-1] != ':' && p[-1] != '\\'
  342. #endif
  343.      ) p--;
  344.  
  345.   if (p == beg)
  346.     return Qnil;
  347. #ifdef MSDOS
  348.   /* Expansion of "c:" to drive and default directory.  */
  349.   if (p == beg + 2 && beg[1] == ':')
  350.     {
  351.       int drive = (*beg) - 'a';
  352.       /* MAXPATHLEN+1 is guaranteed to be enough space for getdefdir.  */
  353.       Bufbyte *res = (Bufbyte *) alloca (MAXPATHLEN + 5);
  354.       if (getdefdir (drive + 1, res + 2)) 
  355.     {
  356.       res[0] = drive + 'a';
  357.       res[1] = ':';
  358.       if (res[strlen ((char *) res) - 1] != '/')
  359.         strcat ((char *) res, "/");
  360.       beg = res;
  361.       p = beg + strlen ((char *) beg);
  362.     }
  363.     }
  364. #endif
  365.   return make_string (beg, p - beg);
  366. }
  367.  
  368. DEFUN ("file-name-nondirectory", Ffile_name_nondirectory, Sfile_name_nondirectory,
  369.   1, 1, 0,
  370.   "Return file name NAME sans its directory.\n\
  371. For example, in a Unix-syntax file name,\n\
  372. this is everything after the last slash,\n\
  373. or the entire name if it contains no slash.")
  374.   (file)
  375.      Lisp_Object file;
  376. {
  377.   /* This function can GC */
  378.   Bufbyte *beg, *p, *end;
  379.   Lisp_Object handler;
  380.  
  381.   CHECK_STRING (file, 0);
  382.  
  383.   /* If the file name has special constructs in it,
  384.      call the corresponding file handler.  */
  385.   handler = Ffind_file_name_handler (file, Qfile_name_nondirectory);
  386.   if (!NILP (handler))
  387.     return (call2_check_string (handler, Qfile_name_nondirectory,
  388.                 file));
  389.  
  390.   beg = string_data (XSTRING (file));
  391.   end = p = beg + string_length (XSTRING (file));
  392.  
  393.   while (p != beg && p[-1] != '/'
  394. #ifdef VMS
  395.      && p[-1] != ':' && p[-1] != ']' && p[-1] != '>'
  396. #endif /* VMS */
  397. #ifdef MSDOS
  398.      && p[-1] != ':' && p[-1] != '\\'
  399. #endif
  400.      ) p--;
  401.  
  402.   return make_string (p, end - p);
  403. }
  404.  
  405. DEFUN ("unhandled-file-name-directory",
  406.        Funhandled_file_name_directory, Sunhandled_file_name_directory, 1, 1, 0,
  407.   "Return a directly usable directory name somehow associated with FILENAME.\n\
  408. A `directly usable' directory name is one that may be used without the\n\
  409. intervention of any file handler.\n\
  410. If FILENAME is a directly usable file itself, return\n\
  411. (file-name-directory FILENAME).\n\
  412. The `call-process' and `start-process' functions use this function to\n\
  413. get a current directory to run processes in.")
  414.   (filename)
  415.     Lisp_Object filename;
  416. {
  417.   /* This function can GC */
  418.   Lisp_Object handler;
  419.  
  420.   /* If the file name has special constructs in it,
  421.      call the corresponding file handler.  */
  422.   handler = Ffind_file_name_handler (filename, Qunhandled_file_name_directory);
  423.   if (!NILP (handler))
  424.     return call2 (handler, Qunhandled_file_name_directory,
  425.           filename);
  426.  
  427.   return Ffile_name_directory (filename);
  428. }
  429.  
  430.  
  431. static char *
  432. file_name_as_directory (char *out, char *in)
  433. {
  434.   int size = strlen (in) - 1;
  435.  
  436.   strcpy (out, in);
  437.  
  438. #ifdef VMS
  439.   /* Is it already a directory string? */
  440.   if (in[size] == ':' || in[size] == ']' || in[size] == '>')
  441.     return out;
  442.   /* Is it a VMS directory file name?  If so, hack VMS syntax.  */
  443.   else if (! strchr (in, '/')
  444.        && ((size > 3 && ! strcmp (&in[size - 3], ".DIR"))
  445.            || (size > 3 && ! strcmp (&in[size - 3], ".dir"))
  446.            || (size > 5 && (! strncmp (&in[size - 5], ".DIR", 4)
  447.                 || ! strncmp (&in[size - 5], ".dir", 4))
  448.            && (in[size - 1] == '.' || in[size - 1] == ';')
  449.            && in[size] == '1')))
  450.     {
  451.       char *p, *dot;
  452.       char brack;
  453.  
  454.       /* x.dir -> [.x]
  455.      dir:x.dir --> dir:[x]
  456.      dir:[x]y.dir --> dir:[x.y] */
  457.       p = in + size;
  458.       while (p != in && *p != ':' && *p != '>' && *p != ']') p--;
  459.       if (p != in)
  460.     {
  461.       strncpy (out, in, p - in);
  462.       out[p - in] = '\0';
  463.       if (*p == ':')
  464.         {
  465.           brack = ']';
  466.           strcat (out, ":[");
  467.         }
  468.       else
  469.         {
  470.           brack = *p;
  471.           strcat (out, ".");
  472.         }
  473.       p++;
  474.     }
  475.       else
  476.     {
  477.       brack = ']';
  478.       strcpy (out, "[.");
  479.     }
  480.       dot = strchr (p, '.');
  481.       if (dot)
  482.     {
  483.       /* blindly remove any extension */
  484.       size = strlen (out) + (dot - p);
  485.       strncat (out, p, dot - p);
  486.     }
  487.       else
  488.     {
  489.       strcat (out, p);
  490.       size = strlen (out);
  491.     }
  492.       out[size++] = brack;
  493.       out[size] = '\0';
  494.     }
  495. #else /* not VMS */
  496.   /* For Unix syntax, Append a slash if necessary */
  497.   if (out[size] != '/'
  498. #ifdef MSDOS
  499.       && out[size] != ':' && out[size] != '/' && out[size] != '\\'
  500. #endif /* MSDOS */
  501.       )
  502.     strcat (out, "/");
  503. #endif /* not VMS */
  504.   return out;
  505. }
  506.  
  507. DEFUN ("file-name-as-directory", Ffile_name_as_directory,
  508.        Sfile_name_as_directory, 1, 1, 0,
  509.   "Return a string representing file FILENAME interpreted as a directory.\n\
  510. This operation exists because a directory is also a file, but its name as\n\
  511. a directory is different from its name as a file.\n\
  512. The result can be used as the value of `default-directory'\n\
  513. or passed as second argument to `expand-file-name'.\n\
  514. For a Unix-syntax file name, just appends a slash.\n\
  515. On VMS, converts \"[X]FOO.DIR\" to \"[X.FOO]\", etc.")
  516.   (file)
  517.      Lisp_Object file;
  518. {
  519.   /* This function can GC */
  520.   char *buf;
  521.   Lisp_Object handler;
  522.  
  523.   CHECK_STRING (file, 0);
  524.  
  525.   /* If the file name has special constructs in it,
  526.      call the corresponding file handler.  */
  527.   handler = Ffind_file_name_handler (file, Qfile_name_as_directory);
  528.   if (!NILP (handler))
  529.     return (call2_check_string (handler, Qfile_name_as_directory,
  530.                 file));
  531.  
  532.   buf = (char *) alloca (string_length (XSTRING (file)) + 10);
  533.   return build_string (file_name_as_directory (buf, (char *) string_data (XSTRING (file))));
  534. }
  535.  
  536. /*
  537.  * Convert from directory name to filename.
  538.  * On VMS:
  539.  *       xyzzy:[mukesh.emacs] => xyzzy:[mukesh]emacs.dir.1
  540.  *       xyzzy:[mukesh] => xyzzy:[000000]mukesh.dir.1
  541.  * On UNIX, it's simple: just make sure there is a terminating /
  542.  
  543.  * Value is nonzero if the string output is different from the input.
  544.  */
  545.  
  546. static int
  547. directory_file_name (CONST char *src, char *dst)
  548. {
  549.   long slen;
  550. #ifdef VMS
  551.   long rlen;
  552.   char * ptr, * rptr;
  553.   char bracket;
  554.   struct FAB fab = cc$rms_fab;
  555.   struct NAM nam = cc$rms_nam;
  556.   char esa[NAM$C_MAXRSS];
  557. #endif /* VMS */
  558.  
  559.   slen = strlen (src);
  560. #ifdef VMS
  561.   if (! strchr (src, '/')
  562.       && (src[slen - 1] == ']'
  563.       || src[slen - 1] == ':'
  564.       || src[slen - 1] == '>'))
  565.     {
  566.       /* VMS style - convert [x.y.z] to [x.y]z, [x] to [000000]x */
  567.       fab.fab$l_fna = src;
  568.       fab.fab$b_fns = slen;
  569.       fab.fab$l_nam = &nam;
  570.       fab.fab$l_fop = FAB$M_NAM;
  571.  
  572.       nam.nam$l_esa = esa;
  573.       nam.nam$b_ess = sizeof esa;
  574.       nam.nam$b_nop |= NAM$M_SYNCHK;
  575.  
  576.       /* We call SYS$PARSE to handle such things as [--] for us. */
  577.       if (SYS$PARSE(&fab, 0, 0) == RMS$_NORMAL)
  578.     {
  579.       slen = nam.nam$b_esl;
  580.       if (esa[slen - 1] == ';' && esa[slen - 2] == '.')
  581.         slen -= 2;
  582.       esa[slen] = '\0';
  583.       src = esa;
  584.     }
  585.       if (src[slen - 1] != ']' && src[slen - 1] != '>')
  586.     {
  587.       /* what about when we have logical_name:???? */
  588.       if (src[slen - 1] == ':')
  589.         {            /* Xlate logical name and see what we get */
  590.           ptr = strcpy (dst, src); /* upper case for getenv */
  591.           while (*ptr)
  592.         {
  593.           *ptr = toupper ((unsigned char) *ptr);
  594.           ptr++;
  595.         }
  596.           dst[slen - 1] = 0;    /* remove colon */
  597.           if (!(src = egetenv (dst)))
  598.         return 0;
  599.           /* should we jump to the beginning of this procedure?
  600.          Good points: allows us to use logical names that xlate
  601.          to Unix names,
  602.          Bad points: can be a problem if we just translated to a device
  603.          name...
  604.          For now, I'll punt and always expect VMS names, and hope for
  605.          the best! */
  606.           slen = strlen (src);
  607.           if (src[slen - 1] != ']' && src[slen - 1] != '>')
  608.         { /* no recursion here! */
  609.           strcpy (dst, src);
  610.           return 0;
  611.         }
  612.         }
  613.       else
  614.         {        /* not a directory spec */
  615.           strcpy (dst, src);
  616.           return 0;
  617.         }
  618.     }
  619.       bracket = src[slen - 1];
  620.  
  621.       /* If bracket is ']' or '>', bracket - 2 is the corresponding
  622.      opening bracket.  */
  623.       ptr = strchr (src, bracket - 2);
  624.       if (ptr == 0)
  625.     { /* no opening bracket */
  626.       strcpy (dst, src);
  627.       return 0;
  628.     }
  629.       if (!(rptr = strrchr (src, '.')))
  630.     rptr = ptr;
  631.       slen = rptr - src;
  632.       strncpy (dst, src, slen);
  633.       dst[slen] = '\0';
  634.       if (*rptr == '.')
  635.     {
  636.       dst[slen++] = bracket;
  637.       dst[slen] = '\0';
  638.     }
  639.       else
  640.     {
  641.       /* If we have the top-level of a rooted directory (i.e. xx:[000000]),
  642.          then translate the device and recurse. */
  643.       if (dst[slen - 1] == ':'
  644.           && dst[slen - 2] != ':'    /* skip decnet nodes */
  645.           && strcmp(src + slen, "[000000]") == 0)
  646.         {
  647.           dst[slen - 1] = '\0';
  648.           if ((ptr = egetenv (dst))
  649.           && (rlen = strlen (ptr) - 1) > 0
  650.           && (ptr[rlen] == ']' || ptr[rlen] == '>')
  651.           && ptr[rlen - 1] == '.')
  652.         {
  653.           char * buf = (char *) alloca (strlen (ptr) + 1);
  654.           strcpy (buf, ptr);
  655.           buf[rlen - 1] = ']';
  656.           buf[rlen] = '\0';
  657.           return directory_file_name (buf, dst);
  658.         }
  659.           else
  660.         dst[slen - 1] = ':';
  661.         }
  662.       strcat (dst, "[000000]");
  663.       slen += 8;
  664.     }
  665.       rptr++;
  666.       rlen = strlen (rptr) - 1;
  667.       strncat (dst, rptr, rlen);
  668.       dst[slen + rlen] = '\0';
  669.       strcat (dst, ".DIR.1");
  670.       return 1;
  671.     }
  672. #endif /* VMS */
  673.   /* Process as Unix format: just remove any final slash.
  674.      But leave "/" unchanged; do not change it to "".  */
  675.   strcpy (dst, src);
  676.   if (slen > 1 
  677. #ifdef MSDOS
  678.       && (dst[slen - 1] == '/' || dst[slen - 1] == '/')
  679.       && dst[slen - 2] != ':'
  680. #else
  681.       && dst[slen - 1] == '/'
  682. #endif
  683.       )
  684.     dst[slen - 1] = 0;
  685.   return 1;
  686. }
  687.  
  688. DEFUN ("directory-file-name", Fdirectory_file_name, Sdirectory_file_name,
  689.   1, 1, 0,
  690.   "Return the file name of the directory named DIR.\n\
  691. This is the name of the file that holds the data for the directory DIR.\n\
  692. This operation exists because a directory is also a file, but its name as\n\
  693. a directory is different from its name as a file.\n\
  694. In Unix-syntax, this function just removes the final slash.\n\
  695. On VMS, given a VMS-syntax directory name such as \"[X.Y]\",\n\
  696. it returns a file name such as \"[X]Y.DIR.1\".")
  697.   (directory)
  698.      Lisp_Object directory;
  699. {
  700.   /* This function can GC */
  701.   char *buf;
  702.   Lisp_Object handler;
  703.  
  704.   CHECK_STRING (directory, 0);
  705.  
  706. #if 0 /* #### WTF? */
  707.   if (NILP (directory))
  708.     return Qnil;
  709. #endif
  710.  
  711.   /* If the file name has special constructs in it,
  712.      call the corresponding file handler.  */
  713.   handler = Ffind_file_name_handler (directory, Qdirectory_file_name);
  714.   if (!NILP (handler))
  715.     return (call2_check_string (handler, Qdirectory_file_name,
  716.                 directory));
  717. #ifdef VMS
  718.   /* 20 extra chars is insufficient for VMS, since we might perform a
  719.      logical name translation. an equivalence string can be up to 255
  720.      chars long, so grab that much extra space...  - sss */
  721.   buf = (char *) alloca (string_length (XSTRING (directory)) + 20 + 255);
  722. #else
  723.   buf = (char *) alloca (string_length (XSTRING (directory)) + 20);
  724. #endif
  725.   directory_file_name ((char *) string_data (XSTRING (directory)), buf);
  726.   return build_string (buf);
  727. }
  728.  
  729. DEFUN ("make-temp-name", Fmake_temp_name, Smake_temp_name, 1, 1, 0,
  730.   "Generate temporary file name (string) starting with PREFIX (a string).\n\
  731. The Emacs process number forms part of the result,\n\
  732. so there is no danger of generating a name being used by another process.")
  733.   (prefix)
  734.      Lisp_Object prefix;
  735. {
  736.   CONST char suffix[] = "XXXXXX";
  737.   char *data;
  738.   int len;
  739.   Lisp_Object val;
  740.  
  741.   CHECK_STRING (prefix, 0);
  742.   len = string_length (XSTRING (prefix));
  743.   val = make_uninit_string (len + countof (suffix) - 1);
  744.   data = (char *) string_data (XSTRING (val));
  745.   memcpy (data, string_data (XSTRING (prefix)), len);
  746.   memcpy (data + len, suffix, countof (suffix));
  747.   mktemp (data);
  748.  
  749.   return val;
  750. }
  751.  
  752. DEFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
  753.   "Convert FILENAME to absolute, and canonicalize it.\n\
  754. Second arg DEFAULT is directory to start with if FILENAME is relative\n\
  755.  (does not start with slash); if DEFAULT is nil or missing,\n\
  756. the current buffer's value of default-directory is used.\n\
  757. Path components that are `.' are removed, and \n\
  758. path components followed by `..' are removed, along with the `..' itself;\n\
  759. note that these simplifications are done without checking the resulting\n\
  760. paths in the file system.\n\
  761. An initial `~/' expands to your home directory.\n\
  762. An initial `~USER/' expands to USER's home directory.\n\
  763. See also the function `substitute-in-file-name'.")
  764.      (name, defalt)
  765.      Lisp_Object name, defalt;
  766. {
  767.   /* This function can GC */
  768.   Bufbyte *nm;
  769.   
  770.   Bufbyte *newdir, *p, *o;
  771.   int tlen;
  772.   Bufbyte *target;
  773.   struct passwd *pw;
  774. #ifdef VMS
  775.   Bufbyte * colon = 0;
  776.   Bufbyte * close = 0;
  777.   Bufbyte * slash = 0;
  778.   Bufbyte * brack = 0;
  779.   int lbrack = 0, rbrack = 0;
  780.   int dots = 0;
  781. #endif /* VMS */
  782. #ifdef MSDOS
  783.   int drive = -1;
  784.   int relpath = 0;
  785.   Bufbyte *tmp, *defdir;
  786. #endif
  787.   Lisp_Object handler;
  788.   
  789.   CHECK_STRING (name, 0);
  790.  
  791.   /* If the file name has special constructs in it,
  792.      call the corresponding file handler.  */
  793.   handler = Ffind_file_name_handler (name, Qexpand_file_name);
  794.   if (!NILP (handler))
  795.     return (call3_check_string (handler, Qexpand_file_name, name,
  796.                 defalt));
  797.  
  798.   /* Use the buffer's default-directory if DEFALT is omitted.  */
  799.   if (NILP (defalt))
  800.     defalt = current_buffer->directory;
  801.   if (NILP (defalt))        /* this should be a meaningful error */
  802.     signal_simple_error ("default-directory is not set",
  803.              make_buffer (current_buffer));
  804.   CHECK_STRING (defalt, 1);
  805.  
  806.   /* Make sure DEFALT is properly expanded.
  807.      It would be better to do this down below where we actually use
  808.      defalt.  Unfortunately, calling Fexpand_file_name recursively
  809.      could invoke GC, and the strings might be relocated.  This would
  810.      be annoying because we have pointers into strings lying around
  811.      that would need adjusting, and people would add new pointers to
  812.      the code and forget to adjust them, resulting in intermittent bugs.
  813.      Putting this call here avoids all that crud.
  814.  
  815.      The EQ test avoids infinite recursion.  */
  816.   if (! NILP (defalt) && !EQ (defalt, name)
  817.       /* This saves time in a common case.  */
  818.       /* #### Unix-specific */
  819.       && string_byte (XSTRING (defalt), 0) != '/')
  820.     {
  821.       struct gcpro gcpro1;
  822.  
  823.       GCPRO1 (name);
  824.       defalt = Fexpand_file_name (defalt, Qnil);
  825.       UNGCPRO;
  826.     }
  827.  
  828. #ifdef VMS
  829.   /* Filenames on VMS are always upper case.  */
  830.   name = Fupcase (name, Fcurrent_buffer ());
  831. #endif
  832. #ifdef FILE_SYSTEM_CASE
  833.   name = FILE_SYSTEM_CASE (name);
  834. #endif
  835.  
  836.   nm = string_data (XSTRING (name));
  837.   
  838. #ifdef MSDOS
  839.   /* First map all backslashes to slashes.  */
  840.   dostounix_filename (nm = strcpy (alloca (strlen (nm) + 1), nm));
  841.  
  842.   /* Now strip drive name. */
  843.   {
  844.     Bufbyte *colon = strrchr (nm, ':');
  845.     if (colon)
  846.       if (nm == colon)
  847.     nm++;
  848.       else
  849.     {
  850.       drive = tolower (colon[-1]) - 'a';
  851.       nm = colon + 1;
  852.       if (*nm != '/')
  853.         {
  854.           defdir = alloca (MAXPATHLEN + 1);
  855.           relpath = getdefdir (drive + 1, defdir);
  856.         }
  857.     }    
  858.   }
  859. #endif
  860.  
  861.   /* If nm is absolute, flush ...// and detect /./ and /../.
  862.      If no /./ or /../ we can return right away. */
  863.   if (
  864.       nm[0] == '/'
  865. #ifdef VMS
  866.       || strchr (nm, ':')
  867. #endif /* VMS */
  868.       )
  869.     {
  870.       /* If it turns out that the filename we want to return is just a
  871.      suffix of FILENAME, we don't need to go through and edit
  872.      things; we just need to construct a new string using data
  873.      starting at the middle of FILENAME.  If we set lose to a
  874.      non-zero value, that means we've discovered that we can't do
  875.      that cool trick.  */
  876.       int lose = 0;
  877.  
  878.       p = nm;
  879.       while (*p)
  880.     {
  881.       /* Since we know the path is absolute, we can assume that each
  882.          element starts with a "/".  */
  883.  
  884.       /* "//" anywhere isn't necessarily hairy; we just start afresh
  885.          with the second slash.  */
  886.       if (p[0] == '/' && p[1] == '/'
  887. #ifdef APOLLO
  888.           /* // at start of filename is meaningful on Apollo system */
  889.           && nm != p
  890. #endif /* APOLLO */
  891.           )
  892.         nm = p + 1;
  893.  
  894.       /* "~" is hairy as the start of any path element.  */
  895.       if (p[0] == '/' && p[1] == '~')
  896.         nm = p + 1, lose = 1;
  897.  
  898.       /* "." and ".." are hairy.  */
  899.       if (p[0] == '/' && p[1] == '.'
  900.           && (p[2] == '/' || p[2] == 0
  901.           || (p[2] == '.' && (p[3] == '/' || p[3] == 0))))
  902.         lose = 1;
  903. #ifdef VMS
  904.       if (p[0] == '\\')
  905.         lose = 1;
  906.       if (p[0] == '/') {
  907.         /* if dev:[dir]/, move nm to / */
  908.         if (!slash && p > nm && (brack || colon)) {
  909.           nm = (brack ? brack + 1 : colon + 1);
  910.           lbrack = rbrack = 0;
  911.           brack = 0;
  912.           colon = 0;
  913.         }
  914.         slash = p;
  915.       }
  916.       if (p[0] == '-')
  917. #ifndef VMS4_4
  918.         /* VMS pre V4.4,convert '-'s in filenames. */
  919.         if (lbrack == rbrack)
  920.           {
  921.         if (dots < 2)    /* this is to allow negative version numbers */
  922.           p[0] = '_';
  923.           }
  924.         else
  925. #endif /* VMS4_4 */
  926.           if (lbrack > rbrack &&
  927.           ((p[-1] == '.' || p[-1] == '[' || p[-1] == '<') &&
  928.            (p[1] == '.' || p[1] == ']' || p[1] == '>')))
  929.         lose = 1;
  930. #ifndef VMS4_4
  931.           else
  932.         p[0] = '_';
  933. #endif /* VMS4_4 */
  934.       /* count open brackets, reset close bracket pointer */
  935.       if (p[0] == '[' || p[0] == '<')
  936.         lbrack++, brack = 0;
  937.       /* count close brackets, set close bracket pointer */
  938.       if (p[0] == ']' || p[0] == '>')
  939.         rbrack++, brack = p;
  940.       /* detect ][ or >< */
  941.       if ((p[0] == ']' || p[0] == '>') && (p[1] == '[' || p[1] == '<'))
  942.         lose = 1;
  943.       if ((p[0] == ':' || p[0] == ']' || p[0] == '>') && p[1] == '~')
  944.         nm = p + 1, lose = 1;
  945.       if (p[0] == ':' && (colon || slash))
  946.         /* if dev1:[dir]dev2:, move nm to dev2: */
  947.         if (brack)
  948.           {
  949.         nm = brack + 1;
  950.         brack = 0;
  951.           }
  952.         /* if /pathname/dev:, move nm to dev: */
  953.         else if (slash)
  954.           nm = slash + 1;
  955.         /* if node::dev:, move colon following dev */
  956.         else if (colon && colon[-1] == ':')
  957.           colon = p;
  958.         /* if dev1:dev2:, move nm to dev2: */
  959.         else if (colon && colon[-1] != ':')
  960.           {
  961.         nm = colon + 1;
  962.         colon = 0;
  963.           }
  964.       if (p[0] == ':' && !colon)
  965.         {
  966.           if (p[1] == ':')
  967.         p++;
  968.           colon = p;
  969.         }
  970.       if (lbrack == rbrack)
  971.         if (p[0] == ';')
  972.           dots = 2;
  973.         else if (p[0] == '.')
  974.           dots++;
  975. #endif /* VMS */
  976.       p++;
  977.     }
  978.       if (!lose)
  979.     {
  980. #ifdef VMS
  981.       if (strchr (nm, '/'))
  982.         return build_string (sys_translate_unix (nm));
  983. #endif /* VMS */
  984. #ifndef MSDOS
  985.       if (nm == string_data (XSTRING (name)))
  986.         return name;
  987.       return build_string ((char *) nm);
  988. #endif
  989.     }
  990.     }
  991.  
  992.   /* Now determine directory to start with and put it in newdir */
  993.  
  994.   newdir = 0;
  995.  
  996.   if (nm[0] == '~')        /* prefix ~ */
  997.   {
  998.     if (nm[1] == '/'
  999. #ifdef VMS
  1000.     || nm[1] == ':'
  1001. #endif /* VMS */
  1002.     || nm[1] == 0)        /* ~ by itself */
  1003.       {
  1004.     if (!(newdir = (Bufbyte *) egetenv ("HOME")))
  1005.       newdir = (Bufbyte *) "";
  1006. #ifdef MSDOS
  1007.       dostounix_filename (newdir);
  1008. #endif
  1009.     nm++;
  1010. #ifdef VMS
  1011.     nm++;            /* Don't leave the slash in nm.  */
  1012. #endif /* VMS */
  1013.       }
  1014.     else            /* ~user/filename */
  1015.       {
  1016.     for (p = nm; *p && (*p != '/'
  1017. #ifdef VMS
  1018.                 && *p != ':'
  1019. #endif /* VMS */
  1020.                 ); p++);
  1021.     o = (Bufbyte *) alloca (p - nm + 1);
  1022.     memcpy (o, (char *) nm, p - nm);
  1023.     o [p - nm] = 0;
  1024.  
  1025.     /* Jamie reports that getpwnam() can get wedged by SIGIO/SIGALARM
  1026.        occurring in it. (It can call select()). */
  1027.     slow_down_interrupts ();
  1028.     pw = (struct passwd *) getpwnam ((char *) o + 1);
  1029.     speed_up_interrupts ();
  1030.     if (pw)
  1031.       {
  1032.         newdir = (Bufbyte *) pw -> pw_dir;
  1033. #ifdef VMS
  1034.         nm = p + 1;        /* skip the terminator */
  1035. #else
  1036.         nm = p;
  1037. #endif /* VMS */
  1038.       }
  1039.  
  1040.     /* If we don't find a user of that name, leave the name
  1041.        unchanged; don't move nm forward to p.  */
  1042.       }
  1043.   }
  1044.  
  1045.   if (nm[0] != '/'
  1046. #ifdef VMS
  1047.       && !strchr (nm, ':')
  1048. #endif /* not VMS */
  1049. #ifdef MSDOS
  1050.       && drive == -1
  1051. #endif
  1052.       && !newdir)
  1053.     {
  1054.       newdir = string_data (XSTRING (defalt));
  1055.     }
  1056.  
  1057. #ifdef MSDOS
  1058.   if (newdir == 0 && relpath)
  1059.     newdir = defdir; 
  1060. #endif
  1061.   if (newdir != 0)
  1062.     {
  1063.       /* Get rid of any slash at the end of newdir.  */
  1064.       int length = strlen ((char *) newdir);
  1065.       /* Adding `length > 1 &&' makes ~ expand into / when homedir
  1066.      is the root dir.  People disagree about whether that is right.
  1067.      Anyway, we can't take the risk of this change now.  */
  1068. #ifdef MSDOS
  1069.       if (newdir[1] != ':' && length > 1)
  1070. #endif
  1071.       if (newdir[length - 1] == '/')
  1072.     {
  1073.       Bufbyte *temp = (Bufbyte *) alloca (length);
  1074.       memcpy (temp, newdir, length - 1);
  1075.       temp[length - 1] = 0;
  1076.       newdir = temp;
  1077.     }
  1078.       tlen = length + 1;
  1079.     }
  1080.   else
  1081.     tlen = 0;
  1082.  
  1083.   /* Now concatenate the directory and name to new space in the stack frame */
  1084.   tlen += strlen ((char *) nm) + 1;
  1085. #ifdef MSDOS
  1086.   /* Add reserved space for drive name.  */
  1087.   target = (Bufbyte *) alloca (tlen + 2) + 2;
  1088. #else
  1089.   target = (Bufbyte *) alloca (tlen);
  1090. #endif
  1091.   *target = 0;
  1092.  
  1093.   if (newdir)
  1094.     {
  1095. #ifndef VMS
  1096.       if (nm[0] == 0 || nm[0] == '/')
  1097.     strcpy ((char *) target, (char *) newdir);
  1098.       else
  1099. #endif
  1100.       file_name_as_directory ((char *) target, (char *) newdir);
  1101.     }
  1102.  
  1103.   strcat ((char *) target, (char *) nm);
  1104. #ifdef VMS
  1105.   if (strchr (target, '/'))
  1106.     strcpy (target, sys_translate_unix (target));
  1107. #endif /* VMS */
  1108.  
  1109.   /* Now canonicalize by removing /. and /foo/.. if they appear.  */
  1110.  
  1111.   p = target;
  1112.   o = target;
  1113.  
  1114.   while (*p)
  1115.     {
  1116. #ifdef VMS
  1117.       if (*p != ']' && *p != '>' && *p != '-')
  1118.     {
  1119.       if (*p == '\\')
  1120.         p++;
  1121.       *o++ = *p++;
  1122.     }
  1123.       else if ((p[0] == ']' || p[0] == '>') && p[0] == p[1] + 2)
  1124.     /* brackets are offset from each other by 2 */
  1125.     {
  1126.       p += 2;
  1127.       if (*p != '.' && *p != '-' && o[-1] != '.')
  1128.         /* convert [foo][bar] to [bar] */
  1129.         while (o[-1] != '[' && o[-1] != '<')
  1130.           o--;
  1131.       else if (*p == '-' && *o != '.')
  1132.         *--p = '.';
  1133.     }
  1134.       else if (p[0] == '-' && o[-1] == '.' &&
  1135.            (p[1] == '.' || p[1] == ']' || p[1] == '>'))
  1136.     /* flush .foo.- ; leave - if stopped by '[' or '<' */
  1137.     {
  1138.       do
  1139.         o--;
  1140.       while (o[-1] != '.' && o[-1] != '[' && o[-1] != '<');
  1141.       if (p[1] == '.')    /* foo.-.bar ==> bar*/
  1142.         p += 2;
  1143.       else if (o[-1] == '.') /* '.foo.-]' ==> ']' */
  1144.         p++, o--;
  1145.       /* else [foo.-] ==> [-] */
  1146.     }
  1147.       else
  1148.     {
  1149. #ifndef VMS4_4
  1150.       if (*p == '-' &&
  1151.           o[-1] != '[' && o[-1] != '<' && o[-1] != '.' &&
  1152.           p[1] != ']' && p[1] != '>' && p[1] != '.')
  1153.         *p = '_';
  1154. #endif /* VMS4_4 */
  1155.       *o++ = *p++;
  1156.     }
  1157. #else /* not VMS */
  1158.       if (*p != '/')
  1159.      {
  1160.       *o++ = *p++;
  1161.     }
  1162.       else if (!strncmp ((char *) p, "//", 2)
  1163. #ifdef APOLLO
  1164.            /* // at start of filename is meaningful in Apollo system */
  1165.            && o != target
  1166. #endif /* APOLLO */
  1167.            )
  1168.     {
  1169.       o = target;
  1170.       p++;
  1171.     }
  1172.       else if (p[0] == '/'
  1173.                && p[1] == '.'
  1174.                && (p[2] == '/' || p[2] == 0))
  1175.     {
  1176.       /* If "/." is the entire filename, keep the "/".  Otherwise,
  1177.          just delete the whole "/.".  */
  1178.       if (o == target && p[2] == '\0')
  1179.         *o++ = *p;
  1180.       p += 2;
  1181.     }
  1182.       else if (!strncmp ((char *) p, "/..", 3)
  1183.            /* `/../' is the "superroot" on certain file systems.  */
  1184.            && o != target
  1185.            && (p[3] == '/' || p[3] == 0))
  1186.     {
  1187.       while (o != target && *--o != '/')
  1188.         ;
  1189. #ifdef APOLLO
  1190.       if (o == target + 1 && o[-1] == '/' && o[0] == '/')
  1191.         ++o;
  1192.       else
  1193. #endif /* APOLLO */
  1194.       if (o == target && *o == '/')
  1195.         ++o;
  1196.       p += 3;
  1197.     }
  1198.       else
  1199.      {
  1200.       *o++ = *p++;
  1201.     }
  1202. #endif /* not VMS */
  1203.     }
  1204.  
  1205. #ifdef MSDOS
  1206.   /* at last, set drive name. */
  1207.   if (target[1] != ':')
  1208.     {
  1209.       target -= 2;
  1210.       target[0] = (drive < 0 ? getdisk () : drive) + 'a';
  1211.       target[1] = ':';
  1212.     }
  1213. #endif
  1214.   return make_string (target, o - target);
  1215. }
  1216.  
  1217. extern char *realpath ();
  1218.  
  1219. DEFUN ("file-truename", Ffile_truename, Sfile_truename, 1, 2, 0,
  1220.   "Return the canonical name of the given FILE.\n\
  1221. Second arg DEFAULT is directory to start with if FILE is relative\n\
  1222.  (does not start with slash); if DEFAULT is nil or missing,\n\
  1223.  the current buffer's value of default-directory is used.\n\
  1224. No component of the resulting pathname will be a symbolic link, as\n\
  1225.  in the realpath() function.")
  1226.      (filename, defalt)
  1227.      Lisp_Object filename, defalt;
  1228. {
  1229.   /* This function can GC */
  1230.   struct gcpro gcpro1;
  1231.   Lisp_Object expanded_name;
  1232.   Lisp_Object handler;
  1233.  
  1234.   CHECK_STRING (filename, 0);
  1235.  
  1236.   GCPRO1 (filename);
  1237.   expanded_name = Fexpand_file_name (filename, defalt);
  1238.   UNGCPRO;
  1239.  
  1240.   if (!STRINGP (expanded_name))
  1241.     return Qnil;
  1242.  
  1243.   GCPRO1 (expanded_name);
  1244.   handler = Ffind_file_name_handler (expanded_name, Qfile_truename);
  1245.   UNGCPRO;
  1246.  
  1247.   if (!NILP (handler))
  1248.     return (call2_check_string (handler, Qfile_truename,
  1249.                 expanded_name));
  1250.  
  1251. #ifdef VMS
  1252.   return (expanded_name);
  1253. #else
  1254.   {
  1255.     char resolved_path[MAXPATHLEN];
  1256.     char path[MAXPATHLEN];
  1257.     char *p = path;
  1258.     int elen = string_length (XSTRING (expanded_name));
  1259.     
  1260.     if (elen >= countof (path))
  1261.       goto toolong;
  1262.     
  1263.     memcpy (path, string_data (XSTRING (expanded_name)), elen + 1);
  1264.     /* memset (resolved_path, 0, sizeof (resolved_path)); */
  1265.  
  1266.     /* Try doing it all at once. */
  1267.     if (!realpath (path, resolved_path))
  1268.     {
  1269.       /* Didn't resolve it -- have to do it one component at a time. */
  1270.       /* "realpath" is a typically useless, stupid un*x piece of crap.
  1271.          It claims to return a useful value in the "error" case, but since
  1272.          there is no indication provided of how far along the pathname
  1273.          the function went before erring, there is no way to use the
  1274.          partial result returned.  What a piece of junk. */
  1275.       for (;;)
  1276.       {
  1277.         p = (char *) memchr (p + 1, '/', elen - (p + 1 - path));
  1278.         if (p)
  1279.           *p = 0;
  1280.  
  1281.         /* memset (resolved_path, 0, sizeof (resolved_path)); */
  1282.         if (realpath (path, resolved_path))
  1283.         {
  1284.           if (p)
  1285.             *p = '/';
  1286.           else
  1287.             break;
  1288.  
  1289.         }
  1290.         else if (errno == ENOENT)
  1291.         {
  1292.           /* Failed on this component.  Just tack on the rest of
  1293.              the string and we are done. */
  1294.           int rlen = strlen (resolved_path);
  1295.  
  1296.           /* "On failure, it returns NULL, sets errno to indicate
  1297.              the error, and places in resolved_path the absolute pathname
  1298.              of the path component which could not be resolved." */
  1299.           if (p)
  1300.           {
  1301.             int plen = elen - (p - path);
  1302.             
  1303.             if (rlen > 1 && resolved_path[rlen - 1] == '/')
  1304.               rlen = rlen - 1;
  1305.  
  1306.             if (plen + rlen + 1 > countof (resolved_path))
  1307.               goto toolong;
  1308.  
  1309.             resolved_path[rlen] = '/';
  1310.             memcpy (resolved_path + rlen + 1, p + 1, plen + 1 - 1);
  1311.           }
  1312.           break;
  1313.         }
  1314.         else
  1315.           goto lose;
  1316.       }
  1317.     }
  1318.  
  1319.     {
  1320.       int rlen = strlen (resolved_path);
  1321.       if (elen > 0 && string_byte (XSTRING (expanded_name), elen - 1) == '/'
  1322.           && !(rlen > 0 && resolved_path[rlen - 1] == '/'))
  1323.       {
  1324.         if (rlen + 1 > countof (resolved_path))
  1325.           goto toolong;
  1326.         resolved_path[rlen] = '/';
  1327.         resolved_path[rlen + 1] = 0;
  1328.         rlen = rlen + 1;
  1329.       }
  1330.       return make_string ((Bufbyte *) resolved_path, rlen);
  1331.     }
  1332.  
  1333.   toolong:
  1334.     errno = ENAMETOOLONG;
  1335.     goto lose;
  1336.   lose:
  1337.     report_file_error ("Finding truename", list1 (expanded_name));
  1338.   }
  1339.   return Qnil;    /* suppress compiler warning */
  1340. #endif /* not VMS */
  1341. }
  1342.  
  1343.  
  1344. DEFUN ("substitute-in-file-name", Fsubstitute_in_file_name,
  1345.   Ssubstitute_in_file_name, 1, 1, 0,
  1346.   "Substitute environment variables referred to in FILENAME.\n\
  1347. `$FOO' where FOO is an environment variable name means to substitute\n\
  1348. the value of that variable.  The variable name should be terminated\n\
  1349. with a character not a letter, digit or underscore; otherwise, enclose\n\
  1350. the entire variable name in braces.\n\
  1351. If `/~' appears, all of FILENAME through that `/' is discarded.\n\n\
  1352. On VMS, `$' substitution is not done; this function does little and only\n\
  1353. duplicates what `expand-file-name' does.")
  1354.   (string)
  1355.      Lisp_Object string;
  1356. {
  1357.   Bufbyte *nm;
  1358.  
  1359.   Bufbyte *s, *p, *o, *x, *endp;
  1360.   Bufbyte *target = 0;
  1361.   int total = 0;
  1362.   int substituted = 0;
  1363.   Bufbyte *xnm;
  1364.   Lisp_Object handler;
  1365.  
  1366.   CHECK_STRING (string, 0);
  1367.  
  1368.   /* If the file name has special constructs in it,
  1369.      call the corresponding file handler.  */
  1370.   handler = Ffind_file_name_handler (string, Qsubstitute_in_file_name);
  1371.   if (!NILP (handler))
  1372.     {
  1373.       Lisp_Object retval = call2 (handler, Qsubstitute_in_file_name,
  1374.                   string);
  1375.  
  1376.       if (!NILP (retval))
  1377.     CHECK_STRING (retval, 0);
  1378.       return retval;
  1379.     }
  1380.  
  1381.   nm = string_data (XSTRING (string));
  1382. #ifdef MSDOS
  1383.   dostounix_filename (nm = strcpy (alloca (strlen (nm) + 1), nm));
  1384.   substituted = !strcmp (nm, string_data (XSTRING (string)));
  1385. #endif
  1386.   endp = nm + string_length (XSTRING (string));
  1387.  
  1388.   /* If /~ or // appears, discard everything through first slash. */
  1389.  
  1390.   for (p = nm; p != endp; p++)
  1391.     {
  1392.       if ((p[0] == '~' ||
  1393. #ifdef APOLLO
  1394.        /* // at start of file name is meaningful in Apollo system */
  1395.        (p[0] == '/' && p - 1 != nm)
  1396. #else /* not APOLLO */
  1397.        p[0] == '/'
  1398. #endif /* not APOLLO */
  1399.        )
  1400.       && p != nm &&
  1401. #ifdef VMS
  1402.       (p[-1] == ':' || p[-1] == ']' || p[-1] == '>' ||
  1403. #endif /* VMS */
  1404.       p[-1] == '/')
  1405. #ifdef VMS
  1406.       )
  1407. #endif /* VMS */
  1408.     {
  1409.       nm = p;
  1410.       substituted = 1;
  1411.     }
  1412. #ifdef MSDOS
  1413.       if (p[0] && p[1] == ':')
  1414.     {
  1415.       nm = p;
  1416.       substituted = 1;
  1417.     }
  1418. #endif /* MSDOS */
  1419.     }
  1420.  
  1421. #ifdef VMS
  1422.   return build_string (nm);
  1423. #else
  1424.  
  1425.   /* See if any variables are substituted into the string
  1426.      and find the total length of their values in `total' */
  1427.  
  1428.   for (p = nm; p != endp;)
  1429.     if (*p != '$')
  1430.       p++;
  1431.     else
  1432.       {
  1433.     p++;
  1434.     if (p == endp)
  1435.       goto badsubst;
  1436.     else if (*p == '$')
  1437.       {
  1438.         /* "$$" means a single "$" */
  1439.         p++;
  1440.         total -= 1;
  1441.         substituted = 1;
  1442.         continue;
  1443.       }
  1444.     else if (*p == '{')
  1445.       {
  1446.         o = ++p;
  1447.         while (p != endp && *p != '}') p++;
  1448.         if (*p != '}') goto missingclose;
  1449.         s = p;
  1450.       }
  1451.     else
  1452.       {
  1453.         o = p;
  1454.         while (p != endp && (isalnum (*p) || *p == '_')) p++;
  1455.         s = p;
  1456.       }
  1457.  
  1458.     /* Copy out the variable name */
  1459.     target = (Bufbyte *) alloca (s - o + 1);
  1460.     strncpy ((char *) target, (char *) o, s - o);
  1461.     target[s - o] = 0;
  1462. #ifdef MSDOS
  1463.     strupr (target); /* $home == $HOME etc.  */
  1464. #endif
  1465.  
  1466.     /* Get variable value */
  1467.     o = (Bufbyte *) egetenv ((char *) target);
  1468.     if (!o) goto badvar;
  1469.     total += strlen ((char *) o);
  1470.     substituted = 1;
  1471.       }
  1472.  
  1473.   if (!substituted)
  1474.     return string;
  1475.  
  1476.   /* If substitution required, recopy the string and do it */
  1477.   /* Make space in stack frame for the new copy */
  1478.   xnm = (Bufbyte *) alloca (string_length (XSTRING (string)) + total + 1);
  1479.   x = xnm;
  1480.  
  1481.   /* Copy the rest of the name through, replacing $ constructs with values */
  1482.   for (p = nm; *p;)
  1483.     if (*p != '$')
  1484.       *x++ = *p++;
  1485.     else
  1486.       {
  1487.     p++;
  1488.     if (p == endp)
  1489.       goto badsubst;
  1490.     else if (*p == '$')
  1491.       {
  1492.         *x++ = *p++;
  1493.         continue;
  1494.       }
  1495.     else if (*p == '{')
  1496.       {
  1497.         o = ++p;
  1498.         while (p != endp && *p != '}') p++;
  1499.         if (*p != '}') goto missingclose;
  1500.         s = p++;
  1501.       }
  1502.     else
  1503.       {
  1504.         o = p;
  1505.         while (p != endp && (isalnum (*p) || *p == '_')) p++;
  1506.         s = p;
  1507.       }
  1508.  
  1509.     /* Copy out the variable name */
  1510.     target = (Bufbyte *) alloca (s - o + 1);
  1511.     strncpy ((char *) target, (char *) o, s - o);
  1512.     target[s - o] = 0;
  1513. #ifdef MSDOS
  1514.     strupr (target); /* $home == $HOME etc.  */
  1515. #endif
  1516.  
  1517.     /* Get variable value */
  1518.     o = (Bufbyte *) egetenv ((char *) target);
  1519.     if (!o)
  1520.       goto badvar;
  1521.  
  1522.     strcpy ((char *) x, (char *) o);
  1523.     x += strlen ((char *) o);
  1524.       }
  1525.  
  1526.   *x = 0;
  1527.  
  1528.   /* If /~ or // appears, discard everything through first slash. */
  1529.  
  1530.   for (p = xnm; p != x; p++)
  1531.     if ((p[0] == '~' ||
  1532. #ifdef APOLLO
  1533.      /* // at start of file name is meaningful in Apollo system */
  1534.      (p[0] == '/' && p - 1 != xnm)
  1535. #else /* not APOLLO */
  1536.      p[0] == '/'
  1537. #endif /* not APOLLO */
  1538.      )
  1539.     && p != nm
  1540.     /* don't do p[-1] if that would go off the beginning --jwz */
  1541.     && (p > xnm && p[-1] == '/'))
  1542.       xnm = p;
  1543. #ifdef MSDOS
  1544.     else if (p[0] && p[1] == ':')
  1545.     xnm = p;
  1546. #endif
  1547.  
  1548.   return make_string (xnm, x - xnm);
  1549.  
  1550.  badsubst:
  1551.   error ("Bad format environment-variable substitution");
  1552.  missingclose:
  1553.   error ("Missing \"}\" in environment-variable substitution");
  1554.  badvar:
  1555.   error ("Substituting nonexistent environment variable \"%s\"",
  1556.      target);
  1557.  
  1558.   /* NOTREACHED */
  1559.   return Qnil;    /* suppress compiler warning */
  1560. #endif /* not VMS */
  1561. }
  1562.  
  1563. /* (directory-file-name (expand-file-name FOO)) */
  1564.  
  1565. Lisp_Object
  1566. expand_and_dir_to_file (Lisp_Object filename, Lisp_Object defdir)
  1567. {
  1568.   /* This function can GC */
  1569.   Lisp_Object abspath;
  1570.   struct gcpro gcpro1;
  1571.  
  1572.   GCPRO1 (filename);
  1573.   abspath = Fexpand_file_name (filename, defdir);
  1574. #ifdef VMS
  1575.   {
  1576.     int c = string_byte (XSTRING (abspath), string_length (XSTRING (abspath)) - 1);
  1577.     if (c == ':' || c == ']' || c == '>')
  1578.       abspath = Fdirectory_file_name (abspath);
  1579.   }
  1580. #else
  1581.   /* Remove final slash, if any (unless path is root).
  1582.      stat behaves differently depending!  */
  1583.   if (string_length (XSTRING (abspath)) > 1
  1584.       && string_byte (XSTRING (abspath), string_length (XSTRING (abspath)) - 1) == '/')
  1585.     /* We cannot take shortcuts; they might be wrong for magic file names.  */
  1586.     abspath = Fdirectory_file_name (abspath);
  1587. #endif
  1588.   UNGCPRO;
  1589.   return abspath;
  1590. }
  1591.  
  1592. static void
  1593. barf_or_query_if_file_exists (Lisp_Object absname, CONST char *querystring,
  1594.                   int interactive)
  1595. {
  1596.   struct stat statbuf;
  1597.  
  1598.   /* stat is a good way to tell whether the file exists,
  1599.      regardless of what access permissions it has.  */
  1600.   if (stat ((char *) string_data (XSTRING (absname)), &statbuf) >= 0)
  1601.     {
  1602.       Lisp_Object tem;
  1603.       struct gcpro gcpro1;
  1604.  
  1605.       GCPRO1 (absname);
  1606.       if (interactive)
  1607.         tem = call1
  1608.       (Qyes_or_no_p,
  1609.        (emacs_doprnt_string_c
  1610.         ((CONST Bufbyte *) GETTEXT ("File %s already exists; %s anyway? "),
  1611.          Qnil, -1, string_data (XSTRING (absname)),
  1612.          GETTEXT (querystring))));
  1613.       else
  1614.         tem = Qnil;
  1615.       UNGCPRO;
  1616.       if (NILP (tem))
  1617.     Fsignal (Qfile_already_exists,
  1618.          list2 (build_translated_string ("File already exists"),
  1619.             absname));
  1620.     }
  1621.   return;
  1622. }
  1623.  
  1624. DEFUN ("copy-file", Fcopy_file, Scopy_file, 2, 4,
  1625.   "fCopy file: \nFCopy %s to file: \np\nP",
  1626.   "Copy FILE to NEWNAME.  Both args must be strings.\n\
  1627. Signals a `file-already-exists' error if file NEWNAME already exists,\n\
  1628. unless a third argument OK-IF-ALREADY-EXISTS is supplied and non-nil.\n\
  1629. A number as third arg means request confirmation if NEWNAME already exists.\n\
  1630. This is what happens in interactive use with M-x.\n\
  1631. Fourth arg KEEP-TIME non-nil means give the new file the same\n\
  1632. last-modified time as the old one.  (This works on only some systems.)\n\
  1633. A prefix arg makes KEEP-TIME non-nil.")
  1634.   (filename, newname, ok_if_already_exists, keep_date)
  1635.      Lisp_Object filename, newname, ok_if_already_exists, keep_date;
  1636. {
  1637.   /* This function can GC */
  1638.   int ifd, ofd, n;
  1639.   char buf[16 * 1024];
  1640.   struct stat st;
  1641.   Lisp_Object handler;
  1642.   int speccount = specpdl_depth ();
  1643.   struct gcpro gcpro1, gcpro2;
  1644.   /* Lisp_Object args[6]; */
  1645.   int input_file_statable_p;
  1646.  
  1647.   GCPRO2 (filename, newname);
  1648.   CHECK_STRING (filename, 0);
  1649.   CHECK_STRING (newname, 1);
  1650.   filename = Fexpand_file_name (filename, Qnil);
  1651.   newname = Fexpand_file_name (newname, Qnil);
  1652.  
  1653.   /* If the input file name has special constructs in it,
  1654.      call the corresponding file handler.  */
  1655.   handler = Ffind_file_name_handler (filename, Qcopy_file);
  1656.   /* Likewise for output file name.  */
  1657.   if (NILP (handler))
  1658.     handler = Ffind_file_name_handler (newname, Qcopy_file);
  1659.   if (!NILP (handler))
  1660.   {
  1661.     UNGCPRO;
  1662.     return call5 (handler, Qcopy_file, filename, newname,
  1663.           ok_if_already_exists, keep_date);
  1664.   }
  1665.  
  1666.   /* When second argument is a directory, copy the file into it.
  1667.      (copy-file "foo" "bar/") == (copy-file "foo" "bar/foo")
  1668.    */
  1669.   if (!NILP (Ffile_directory_p (newname)))
  1670.     {
  1671.       Lisp_Object args[3];
  1672.       struct gcpro gcpro1;
  1673.       int i = 1;
  1674.  
  1675.       args[0] = newname; 
  1676.       args[1] = Qnil; args[2] = Qnil;
  1677.       GCPRO1 (*args); 
  1678.       gcpro1.nvars = 3;
  1679.       if (string_byte (XSTRING (newname),
  1680.                string_length (XSTRING (newname)) - 1) != '/')
  1681.     args[i++] = build_string ("/");
  1682.       args[i++] = Ffile_name_nondirectory (filename);
  1683.       newname = Fconcat (i, args);
  1684.       UNGCPRO;
  1685.     }
  1686.  
  1687.   if (NILP (ok_if_already_exists)
  1688.       || INTP (ok_if_already_exists))
  1689.     barf_or_query_if_file_exists (newname, "copy to it",
  1690.                   INTP (ok_if_already_exists));
  1691.  
  1692.   ifd = open ((char *) string_data (XSTRING (filename)), O_RDONLY, 0);
  1693.   if (ifd < 0)
  1694.     report_file_error ("Opening input file", Fcons (filename, Qnil));
  1695.  
  1696.   record_unwind_protect (close_file_unwind, make_number (ifd));
  1697.  
  1698.   /* We can only copy regular files and symbolic links.  Other files are not
  1699.      copyable by us. */
  1700.   input_file_statable_p = (fstat (ifd, &st) >= 0);
  1701.  
  1702. #if defined (S_ISREG) && defined (S_ISLNK)
  1703.   if (input_file_statable_p)
  1704.     {
  1705.       if (!(S_ISREG (st.st_mode))
  1706.       /* XEmacs: have to allow S_ISCHR in order to copy /dev/null */
  1707. #ifdef S_ISCHR
  1708.       && !(S_ISCHR (st.st_mode))
  1709. #endif
  1710.       && !(S_ISLNK (st.st_mode)))
  1711.     {
  1712. #if defined (EISDIR)
  1713.       /* Get a better looking error message. */
  1714.       errno = EISDIR;
  1715. #endif /* EISDIR */
  1716.     report_file_error ("Non-regular file", Fcons (filename, Qnil));
  1717.     }
  1718.     }
  1719. #endif /* S_ISREG && S_ISLNK */
  1720.  
  1721. #ifdef VMS
  1722.   /* Create the copy file with the same record format as the input file */
  1723.   ofd = sys_creat ((char *) string_data (XSTRING (newname)), 0666, ifd);
  1724. #else
  1725. #ifdef MSDOS
  1726.   /* System's default file type was set to binary by _fmode in emacs.c.  */
  1727.   ofd = creat ((char *) string_data (XSTRING (newname)), S_IREAD | S_IWRITE);
  1728. #else /* not MSDOS */
  1729.   ofd = creat ((char *) string_data (XSTRING (newname)), 0666);
  1730. #endif /* not MSDOS */
  1731. #endif /* VMS */
  1732.   if (ofd < 0)
  1733.     report_file_error ("Opening output file", list1 (newname));
  1734.  
  1735.   {
  1736.     Lisp_Object ofd_locative = list1 (make_number (ofd));
  1737.  
  1738.     record_unwind_protect (close_file_unwind, ofd_locative);
  1739.  
  1740.     while ((n = read_allowing_quit (ifd, buf, sizeof (buf))) > 0)
  1741.     {
  1742.       if (write_allowing_quit (ofd, buf, n) != n)
  1743.     report_file_error ("I/O error", list1 (newname));
  1744.     }
  1745.  
  1746.     /* Closing the output clobbers the file times on some systems.  */
  1747.     if (close (ofd) < 0)
  1748.       report_file_error ("I/O error", Fcons (newname, Qnil));
  1749.  
  1750.     if (input_file_statable_p)
  1751.     {
  1752.       if (!NILP (keep_date))
  1753.       {
  1754.         EMACS_TIME atime, mtime;
  1755.         EMACS_SET_SECS_USECS (atime, st.st_atime, 0);
  1756.         EMACS_SET_SECS_USECS (mtime, st.st_mtime, 0);
  1757.         set_file_times ((char *) string_data (XSTRING (newname)), atime,
  1758.             mtime);
  1759.       }
  1760. #ifdef APOLLO
  1761.       if (!egetenv ("USE_DOMAIN_ACLS"))
  1762. #endif
  1763.     chmod ((char *) string_data (XSTRING (newname)), st.st_mode & 07777);
  1764.     }
  1765.  
  1766.     /* We'll close it by hand */
  1767.     XCAR (ofd_locative) = Qnil;
  1768.  
  1769.     /* Close ifd */
  1770.     unbind_to (speccount, Qnil);
  1771.   }
  1772.  
  1773.   UNGCPRO;
  1774.   return Qnil;
  1775. }
  1776.  
  1777. DEFUN ("make-directory-internal", Fmake_directory_internal,
  1778.        Smake_directory_internal, 1, 1, 0,
  1779.   "Create a directory.  One argument, a file name string.")
  1780.   (dirname)
  1781.      Lisp_Object dirname;
  1782. {
  1783.   /* This function can GC */
  1784.   char dir [MAXPATHLEN];
  1785.   Lisp_Object handler;
  1786.  
  1787.   struct gcpro gcpro1;
  1788.   
  1789.   GCPRO1 (dirname);
  1790.   CHECK_STRING (dirname, 0);
  1791.   dirname = Fexpand_file_name (dirname, Qnil);
  1792.  
  1793.   handler = Ffind_file_name_handler (dirname, Qmake_directory_internal);
  1794.   UNGCPRO;
  1795.   if (!NILP (handler))
  1796.     return (call2 (handler, Qmake_directory_internal,
  1797.            dirname));
  1798.  
  1799.   if (string_length (XSTRING (dirname)) > (sizeof (dir) - 1))
  1800.     {
  1801.       return Fsignal (Qfile_error,
  1802.               list3 (build_translated_string ("Creating directory"),
  1803.                  build_translated_string ("pathame too long"),
  1804.                  dirname));
  1805.     }
  1806.   strncpy (dir, (char *) string_data (XSTRING (dirname)),
  1807.        string_length (XSTRING (dirname)) + 1);
  1808.  
  1809. #ifndef VMS
  1810.   if (dir [string_length (XSTRING (dirname)) - 1] == '/')
  1811.     dir [string_length (XSTRING (dirname)) - 1] = 0;
  1812. #endif
  1813.  
  1814.   if (mkdir (dir, 0777) != 0)
  1815.     report_file_error ("Creating directory", list1 (dirname));
  1816.  
  1817.   return Qnil;
  1818. }
  1819.  
  1820. DEFUN ("delete-directory", Fdelete_directory, Sdelete_directory, 1, 1,
  1821.        "FDelete directory: ",
  1822.   "Delete a directory.  One argument, a file name or directory name string.")
  1823.   (dirname)
  1824.      Lisp_Object dirname;
  1825. {
  1826.   /* This function can GC */
  1827.   Lisp_Object handler;
  1828.   struct gcpro gcpro1;
  1829.   
  1830.   GCPRO1 (dirname);
  1831.   CHECK_STRING (dirname, 0);
  1832.   dirname =
  1833.     Fdirectory_file_name (Fexpand_file_name (dirname, Qnil));
  1834.  
  1835.   handler = Ffind_file_name_handler (dirname, Qdelete_directory);
  1836.   UNGCPRO;
  1837.   if (!NILP (handler))
  1838.     return (call2 (handler, Qdelete_directory, dirname));
  1839.  
  1840.   if (rmdir ((char *) string_data (XSTRING (dirname))) != 0)
  1841.     report_file_error ("Removing directory", list1 (dirname));
  1842.  
  1843.   return Qnil;
  1844. }
  1845.  
  1846. DEFUN ("delete-file", Fdelete_file, Sdelete_file, 1, 1, "fDelete file: ",
  1847.   "Delete specified file.  One argument, a file name string.\n\
  1848. If file has multiple names, it continues to exist with the other names.")
  1849.   (filename)
  1850.      Lisp_Object filename;
  1851. {
  1852.   /* This function can GC */
  1853.   Lisp_Object handler;
  1854.   struct gcpro gcpro1;
  1855.   
  1856.   GCPRO1 (filename);
  1857.   CHECK_STRING (filename, 0);
  1858.   filename = Fexpand_file_name (filename, Qnil);
  1859.  
  1860.   handler = Ffind_file_name_handler (filename, Qdelete_file);
  1861.   UNGCPRO;
  1862.   if (!NILP (handler))
  1863.     return call2 (handler, Qdelete_file, filename);
  1864.  
  1865.   if (0 > unlink ((char *) string_data (XSTRING (filename))))
  1866.     report_file_error ("Removing old name", list1 (filename));
  1867.   return Qnil;
  1868. }
  1869.  
  1870. DEFUN ("rename-file", Frename_file, Srename_file, 2, 3,
  1871.   "fRename file: \nFRename %s to file: \np",
  1872.   "Rename FILE as NEWNAME.  Both args strings.\n\
  1873. If file has names other than FILE, it continues to have those names.\n\
  1874. Signals a `file-already-exists' error if a file NEWNAME already exists\n\
  1875. unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.\n\
  1876. A number as third arg means request confirmation if NEWNAME already exists.\n\
  1877. This is what happens in interactive use with M-x.")
  1878.   (filename, newname, ok_if_already_exists)
  1879.      Lisp_Object filename, newname, ok_if_already_exists;
  1880. {
  1881.   /* This function can GC */
  1882.   Lisp_Object handler;
  1883.   struct gcpro gcpro1, gcpro2;
  1884.  
  1885.   GCPRO2 (filename, newname);
  1886.   CHECK_STRING (filename, 0);
  1887.   CHECK_STRING (newname, 1);
  1888.   filename = Fexpand_file_name (filename, Qnil);
  1889.   newname = Fexpand_file_name (newname, Qnil);
  1890.  
  1891.   /* If the file name has special constructs in it,
  1892.      call the corresponding file handler.  */
  1893.   handler = Ffind_file_name_handler (filename, Qrename_file);
  1894.   if (NILP (handler))
  1895.     handler = Ffind_file_name_handler (newname, Qrename_file);
  1896.   if (!NILP (handler))
  1897.   {
  1898.     UNGCPRO;
  1899.     return call4 (handler, Qrename_file,
  1900.           filename, newname, ok_if_already_exists);
  1901.   }
  1902.  
  1903.   /* When second argument is a directory, rename the file into it.
  1904.      (rename-file "foo" "bar/") == (rename-file "foo" "bar/foo")
  1905.    */
  1906.   if (!NILP (Ffile_directory_p (newname)))
  1907.     {
  1908.       Lisp_Object args[3];
  1909.       struct gcpro gcpro1;
  1910.       int i = 1;
  1911.  
  1912.       args[0] = newname; 
  1913.       args[1] = Qnil; args[2] = Qnil;
  1914.       GCPRO1 (*args); 
  1915.       gcpro1.nvars = 3;
  1916.       if (string_byte (XSTRING (newname),
  1917.                string_length (XSTRING (newname)) - 1) != '/')
  1918.     args[i++] = build_string ("/");
  1919.       args[i++] = Ffile_name_nondirectory (filename);
  1920.       newname = Fconcat (i, args);
  1921.       UNGCPRO;
  1922.     }
  1923.  
  1924.   if (NILP (ok_if_already_exists)
  1925.       || INTP (ok_if_already_exists))
  1926.     barf_or_query_if_file_exists (newname, "rename to it",
  1927.                   INTP (ok_if_already_exists));
  1928.  
  1929.   if (0 > rename ((char *) string_data (XSTRING (filename)),
  1930.           (char *) string_data (XSTRING (newname))))
  1931.     {
  1932.       if (errno == EXDEV)
  1933.     {
  1934.       Fcopy_file (filename, newname,
  1935.               /* We have already prompted if it was an integer,
  1936.              so don't have copy-file prompt again.  */
  1937.               ((NILP (ok_if_already_exists)) ? Qnil : Qt),
  1938.                       Qt);
  1939.       Fdelete_file (filename);
  1940.     }
  1941.       else
  1942.     {
  1943.       report_file_error ("Renaming", list2 (filename, newname));
  1944.     }
  1945.     }
  1946.   UNGCPRO;
  1947.   return Qnil;
  1948. }
  1949.  
  1950. DEFUN ("add-name-to-file", Fadd_name_to_file, Sadd_name_to_file, 2, 3,
  1951.   "fAdd name to file: \nFName to add to %s: \np",
  1952.   "Give FILE additional name NEWNAME.  Both args strings.\n\
  1953. Signals a `file-already-exists' error if a file NEWNAME already exists\n\
  1954. unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.\n\
  1955. A number as third arg means request confirmation if NEWNAME already exists.\n\
  1956. This is what happens in interactive use with M-x.")
  1957.   (filename, newname, ok_if_already_exists)
  1958.      Lisp_Object filename, newname, ok_if_already_exists;
  1959. {
  1960.   /* This function can GC */
  1961.   Lisp_Object handler;
  1962.   struct gcpro gcpro1, gcpro2;
  1963.  
  1964.   GCPRO2 (filename, newname);
  1965.   CHECK_STRING (filename, 0);
  1966.   CHECK_STRING (newname, 1);
  1967.   filename = Fexpand_file_name (filename, Qnil);
  1968.   newname = Fexpand_file_name (newname, Qnil);
  1969.  
  1970.   /* If the file name has special constructs in it,
  1971.      call the corresponding file handler.  */
  1972.   handler = Ffind_file_name_handler (filename, Qadd_name_to_file);
  1973.   if (!NILP (handler))
  1974.     {
  1975.       UNGCPRO;
  1976.       return call3 (handler, Qadd_name_to_file, filename,
  1977.             newname);
  1978.     }
  1979.  
  1980.   if (NILP (ok_if_already_exists)
  1981.       || INTP (ok_if_already_exists))
  1982.     barf_or_query_if_file_exists (newname, "make it a new name",
  1983.                   INTP (ok_if_already_exists));
  1984.  
  1985.   unlink ((char *) string_data (XSTRING (newname)));
  1986.   if (0 > link ((char *) string_data (XSTRING (filename)),
  1987.         (char *) string_data (XSTRING (newname))))
  1988.     {
  1989.       report_file_error ("Adding new name",
  1990.              list2 (filename, newname));
  1991.     }
  1992.  
  1993.   UNGCPRO;
  1994.   return Qnil;
  1995. }
  1996.  
  1997. #ifdef S_IFLNK
  1998. DEFUN ("make-symbolic-link", Fmake_symbolic_link, Smake_symbolic_link, 2, 3,
  1999.   "FMake symbolic link to file: \nFMake symbolic link to file %s: \np",
  2000.   "Make a symbolic link to FILENAME, named LINKNAME.  Both args strings.\n\
  2001. Signals a `file-already-exists' error if a file NEWNAME already exists\n\
  2002. unless optional third argument OK-IF-ALREADY-EXISTS is non-nil.\n\
  2003. A number as third arg means request confirmation if NEWNAME already exists.\n\
  2004. This happens for interactive use with M-x.")
  2005.   (filename, linkname, ok_if_already_exists)
  2006.      Lisp_Object filename, linkname, ok_if_already_exists;
  2007. {
  2008.   /* This function can GC */
  2009.   Lisp_Object handler;
  2010.   struct gcpro gcpro1, gcpro2;
  2011.  
  2012.   GCPRO2 (filename, linkname);
  2013.   CHECK_STRING (filename, 0);
  2014.   CHECK_STRING (linkname, 1);
  2015.   /* If the link target has a ~, we must expand it to get
  2016.      a truly valid file name.  Otherwise, do not expand;
  2017.      we want to permit links to relative file names.  */
  2018.   if (string_byte (XSTRING (filename), 0) == '~') /* #### Un*x-specific */
  2019.     filename = Fexpand_file_name (filename, Qnil);
  2020.   linkname = Fexpand_file_name (linkname, Qnil);
  2021.  
  2022.   /* If the file name has special constructs in it,
  2023.      call the corresponding file handler.  */
  2024.   handler = Ffind_file_name_handler (filename, Qmake_symbolic_link);
  2025.   if (!NILP (handler))
  2026.   {
  2027.     UNGCPRO;
  2028.     return call4 (handler, Qmake_symbolic_link, filename, linkname,
  2029.           ok_if_already_exists);
  2030.   }
  2031.  
  2032.   if (NILP (ok_if_already_exists)
  2033.       || INTP (ok_if_already_exists))
  2034.     barf_or_query_if_file_exists (linkname, "make it a link",
  2035.                   INTP (ok_if_already_exists));
  2036.  
  2037.   unlink ((char *) string_data (XSTRING (linkname)));
  2038.   if (0 > symlink ((char *) string_data (XSTRING (filename)),
  2039.            (char *) string_data (XSTRING (linkname))))
  2040.     {
  2041.       report_file_error ("Making symbolic link",
  2042.              list2 (filename, linkname));
  2043.     }
  2044.   UNGCPRO;
  2045.   return Qnil;
  2046. }
  2047. #endif /* S_IFLNK */
  2048.  
  2049. #ifdef VMS
  2050.  
  2051. DEFUN ("define-logical-name", Fdefine_logical_name, Sdefine_logical_name,
  2052.        2, 2, "sDefine logical name: \nsDefine logical name %s as: ",
  2053.   "Define the job-wide logical name NAME to have the value STRING.\n\
  2054. If STRING is nil or a null string, the logical name NAME is deleted.")
  2055.   (varname, string)
  2056.      Lisp_Object varname;
  2057.      Lisp_Object string;
  2058. {
  2059.   CHECK_STRING (varname, 0);
  2060.   if (NILP (string))
  2061.     delete_logical_name ((char *) string_data (XSTRING (varname)));
  2062.   else
  2063.     {
  2064.       CHECK_STRING (string, 1);
  2065.  
  2066.       if (string_length (XSTRING (string)) == 0)
  2067.         delete_logical_name ((char *) string_data (XSTRING (varname)));
  2068.       else
  2069.         define_logical_name ((char *) string_data (XSTRING (varname)), (char *) string_data (XSTRING (string)));
  2070.     }
  2071.  
  2072.   return string;
  2073. }
  2074. #endif /* VMS */
  2075.  
  2076. #ifdef HPUX_NET
  2077.  
  2078. DEFUN ("sysnetunam", Fsysnetunam, Ssysnetunam, 2, 2, 0,
  2079.        "Open a network connection to PATH using LOGIN as the login string.")
  2080.      (path, login)
  2081.      Lisp_Object path, login;
  2082. {
  2083.   int netresult;
  2084.   
  2085.   CHECK_STRING (path, 0);
  2086.   CHECK_STRING (login, 0);  
  2087.  
  2088.   /* netunam, being a strange-o system call only used once, is not
  2089.      encapsulated. */
  2090.   netresult = netunam (string_ext_data (XSTRING (path)),
  2091.                string_ext_data2 (XSTRING (login)));
  2092.  
  2093.   if (netresult == -1)
  2094.     return Qnil;
  2095.   else
  2096.     return Qt;
  2097. }
  2098. #endif /* HPUX_NET */
  2099.  
  2100. DEFUN ("file-name-absolute-p", Ffile_name_absolute_p, Sfile_name_absolute_p,
  2101.        1, 1, 0,
  2102.        "Return t if file FILENAME specifies an absolute path name.\n\
  2103. On Unix, this is a name starting with a `/' or a `~'.")
  2104.      (filename)
  2105.      Lisp_Object filename;
  2106. {
  2107.   Bufbyte *ptr;
  2108.  
  2109.   CHECK_STRING (filename, 0);
  2110.   ptr = string_data (XSTRING (filename));
  2111.   if (*ptr == '/' || *ptr == '~'
  2112. #ifdef VMS
  2113. /* ??? This criterion is probably wrong for '<'.  */
  2114.       || strchr (ptr, ':') || strchr (ptr, '<')
  2115.       || (*ptr == '[' && (ptr[1] != '-' || (ptr[2] != '.' && ptr[2] != ']'))
  2116.       && ptr[1] != '.')
  2117. #endif /* VMS */
  2118. #ifdef MSDOS
  2119.       || (*ptr != 0 && ptr[1] == ':' && (ptr[2] == '/' || ptr[2] == '\\'))
  2120. #endif /* MSDOS */
  2121.       )
  2122.     return Qt;
  2123.   else
  2124.     return Qnil;
  2125. }
  2126.  
  2127. DEFUN ("file-exists-p", Ffile_exists_p, Sfile_exists_p, 1, 1, 0,
  2128.   "Return t if file FILENAME exists.  (This does not mean you can read it.)\n\
  2129. See also `file-readable-p' and `file-attributes'.")
  2130.   (filename)
  2131.      Lisp_Object filename;
  2132. {
  2133.   /* This function can GC */
  2134.   Lisp_Object abspath;
  2135.   Lisp_Object handler;
  2136.   struct stat statbuf;
  2137.   struct gcpro gcpro1;
  2138.   
  2139.   GCPRO1 (filename);
  2140.   CHECK_STRING (filename, 0);
  2141.   abspath = Fexpand_file_name (filename, Qnil);
  2142.   UNGCPRO;
  2143.  
  2144.   /* If the file name has special constructs in it,
  2145.      call the corresponding file handler.  */
  2146.   GCPRO1 (abspath);
  2147.   handler = Ffind_file_name_handler (abspath, Qfile_exists_p);
  2148.   UNGCPRO;
  2149.   if (!NILP (handler))
  2150.     return call2 (handler, Qfile_exists_p, abspath);
  2151.  
  2152.   if (stat ((char *) string_data (XSTRING (abspath)), &statbuf) >= 0)
  2153.     return (Qt);
  2154.   else
  2155.     return (Qnil);
  2156. }
  2157.  
  2158. DEFUN ("file-executable-p", Ffile_executable_p, Sfile_executable_p, 1, 1, 0,
  2159.   "Return t if FILENAME can be executed by you.\n\
  2160. For a directory, this means you can access files in that directory.")
  2161.   (filename)
  2162.     Lisp_Object filename;
  2163.  
  2164. {
  2165.   /* This function can GC */
  2166.   Lisp_Object abspath;
  2167.   Lisp_Object handler;
  2168.   struct gcpro gcpro1;
  2169.   
  2170.   GCPRO1 (filename);
  2171.   CHECK_STRING (filename, 0);
  2172.   abspath = Fexpand_file_name (filename, Qnil);
  2173.   UNGCPRO;
  2174.  
  2175.   /* If the file name has special constructs in it,
  2176.      call the corresponding file handler.  */
  2177.   GCPRO1 (abspath);
  2178.   handler = Ffind_file_name_handler (abspath, Qfile_executable_p);
  2179.   UNGCPRO;
  2180.   if (!NILP (handler))
  2181.     return call2 (handler, Qfile_executable_p, abspath);
  2182.  
  2183.   if (access ((char *) string_data (XSTRING (abspath)), 1) >= 0)
  2184.     return (Qt);
  2185.   else
  2186.     return (Qnil);
  2187. }
  2188.  
  2189. DEFUN ("file-readable-p", Ffile_readable_p, Sfile_readable_p, 1, 1, 0,
  2190.   "Return t if file FILENAME exists and you can read it.\n\
  2191. See also `file-exists-p' and `file-attributes'.")
  2192.   (filename)
  2193.      Lisp_Object filename;
  2194. {
  2195.   /* This function can GC */
  2196.   Lisp_Object abspath;
  2197.   Lisp_Object handler;
  2198.   int desc;
  2199.   struct gcpro gcpro1;
  2200.   
  2201.   GCPRO1 (filename);
  2202.   CHECK_STRING (filename, 0);
  2203.   abspath = Fexpand_file_name (filename, Qnil);
  2204.   UNGCPRO;
  2205.  
  2206.   /* If the file name has special constructs in it,
  2207.      call the corresponding file handler.  */
  2208.   GCPRO1 (abspath);
  2209.   handler = Ffind_file_name_handler (abspath, Qfile_readable_p);
  2210.   UNGCPRO;
  2211.   if (!NILP (handler))
  2212.     return call2 (handler, Qfile_readable_p, abspath);
  2213.  
  2214.   desc = open ((char *) string_data (XSTRING (abspath)), O_RDONLY, 0);
  2215.   if (desc < 0)
  2216.     return Qnil;
  2217.   close (desc);
  2218.   return Qt;
  2219. }
  2220.  
  2221. DEFUN ("file-symlink-p", Ffile_symlink_p, Sfile_symlink_p, 1, 1, 0,
  2222.   "Return non-nil if file FILENAME is the name of a symbolic link.\n\
  2223. The value is the name of the file to which it is linked.\n\
  2224. Otherwise returns nil.")
  2225.   (filename)
  2226.      Lisp_Object filename;
  2227. {
  2228.   /* This function can GC */
  2229. #ifdef S_IFLNK
  2230.   char *buf;
  2231.   int bufsize;
  2232.   int valsize;
  2233.   Lisp_Object val;
  2234.   Lisp_Object handler;
  2235.   struct gcpro gcpro1;
  2236.   
  2237.   GCPRO1 (filename);
  2238.   CHECK_STRING (filename, 0);
  2239.   filename = Fexpand_file_name (filename, Qnil);
  2240.   UNGCPRO;
  2241.  
  2242.   /* If the file name has special constructs in it,
  2243.      call the corresponding file handler.  */
  2244.   handler = Ffind_file_name_handler (filename, Qfile_symlink_p);
  2245.   if (!NILP (handler))
  2246.     return call2 (handler, Qfile_symlink_p, filename);
  2247.  
  2248.   bufsize = 100;
  2249.   while (1)
  2250.     {
  2251.       buf = (char *) xmalloc (bufsize);
  2252.       memset (buf, 0, bufsize);
  2253.       valsize = readlink ((char *) string_data (XSTRING (filename)),
  2254.               buf, bufsize);
  2255.       if (valsize < bufsize) break;
  2256.       /* Buffer was not long enough */
  2257.       xfree (buf);
  2258.       bufsize *= 2;
  2259.     }
  2260.   if (valsize == -1)
  2261.     {
  2262.       xfree (buf);
  2263.       return Qnil;
  2264.     }
  2265.   val = make_string ((Bufbyte *) buf, valsize);
  2266.   xfree (buf);
  2267.   return val;
  2268. #else /* not S_IFLNK */
  2269.   return Qnil;
  2270. #endif /* not S_IFLNK */
  2271. }
  2272.  
  2273. #ifdef SOLARIS_BROKEN_ACCESS
  2274. /* In Solaris 2.1, the readonly-ness of the filesystem is not
  2275.    considered by the access system call.  This is Sun's bug, but we
  2276.    still have to make Emacs work.  */
  2277.  
  2278. #include <sys/statvfs.h>
  2279.  
  2280. static int
  2281. ro_fsys (char *path)
  2282. {
  2283.     struct statvfs statvfsb;
  2284.  
  2285.     /* statvfs, being a strange-o system call only used once, is not
  2286.        encapsulated. */
  2287.     if (statvfs (c_charptr_to_external (path), &statvfsb))
  2288.       return 1;  /* error from statvfs, be conservative and say not wrtable */
  2289.     else
  2290.       /* Otherwise, fsys is ro if bit is set.  */
  2291.       return statvfsb.f_flag & ST_RDONLY;
  2292. }
  2293. #else
  2294. /* But on every other os, access has already done the right thing.  */
  2295. #define ro_fsys(path) 0
  2296. #endif
  2297.  
  2298. /* Having this before file-symlink-p mysteriously caused it to be forgotten
  2299.    on the RT/PC.  */
  2300. DEFUN ("file-writable-p", Ffile_writable_p, Sfile_writable_p, 1, 1, 0,
  2301.   "Return t if file FILENAME can be written or created by you.")
  2302.   (filename)
  2303.      Lisp_Object filename;
  2304. {
  2305.   /* This function can GC */
  2306.   Lisp_Object abspath, dir;
  2307.   Lisp_Object handler;
  2308.   struct gcpro gcpro1;
  2309.   
  2310.   GCPRO1 (filename);
  2311.   CHECK_STRING (filename, 0);
  2312.   abspath = Fexpand_file_name (filename, Qnil);
  2313.   UNGCPRO;
  2314.  
  2315.   /* If the file name has special constructs in it,
  2316.      call the corresponding file handler.  */
  2317.   GCPRO1 (abspath);
  2318.   handler = Ffind_file_name_handler (abspath, Qfile_writable_p);
  2319.   UNGCPRO;
  2320.   if (!NILP (handler))
  2321.     return call2 (handler, Qfile_writable_p, abspath);
  2322.  
  2323.   if (access ((char *) string_data (XSTRING (abspath)), 0) >= 0)
  2324.     {
  2325.       if (access ((char *) string_data (XSTRING (abspath)), 2) >= 0
  2326.           && ! ro_fsys ((char *) string_data (XSTRING (abspath))))
  2327.     return (Qt);
  2328.       else
  2329.     return (Qnil);
  2330.     }
  2331.  
  2332.   dir = Ffile_name_directory (abspath);
  2333. #if defined (VMS) || defined (MSDOS)
  2334.   if (!NILP (dir))
  2335.     dir = Fdirectory_file_name (dir);
  2336. #endif /* VMS or MSDOS */
  2337.   if (access (!NILP (dir) ? (char *) string_data (XSTRING (dir)) : "", 2) >= 0
  2338.       && ! ro_fsys ((char *) string_data (XSTRING (dir))))
  2339.     return (Qt);
  2340.   else
  2341.     return (Qnil);
  2342. }
  2343.  
  2344. DEFUN ("file-directory-p", Ffile_directory_p, Sfile_directory_p, 1, 1, 0,
  2345.   "Return t if file FILENAME is the name of a directory as a file.\n\
  2346. A directory name spec may be given instead; then the value is t\n\
  2347. if the directory so specified exists and really is a directory.")
  2348.   (filename)
  2349.      Lisp_Object filename;
  2350. {
  2351.   /* This function can GC */
  2352.   Lisp_Object abspath;
  2353.   struct stat st;
  2354.   Lisp_Object handler;
  2355.   struct gcpro gcpro1;
  2356.   
  2357.   GCPRO1 (filename);
  2358.   abspath = expand_and_dir_to_file (filename,
  2359.                     current_buffer->directory);
  2360.   UNGCPRO;
  2361.  
  2362.   /* If the file name has special constructs in it,
  2363.      call the corresponding file handler.  */
  2364.   GCPRO1 (abspath);
  2365.   handler = Ffind_file_name_handler (abspath, Qfile_directory_p);
  2366.   UNGCPRO;
  2367.   if (!NILP (handler))
  2368.     return call2 (handler, Qfile_directory_p, abspath);
  2369.  
  2370.   if (stat ((char *) string_data (XSTRING (abspath)), &st) < 0)
  2371.     return Qnil;
  2372.   return (st.st_mode & S_IFMT) == S_IFDIR ? Qt : Qnil;
  2373. }
  2374.  
  2375. DEFUN ("file-accessible-directory-p",
  2376.        Ffile_accessible_directory_p, Sfile_accessible_directory_p, 1, 1, 0,
  2377.   "Return t if file FILENAME is the name of a directory as a file,\n\
  2378. and files in that directory can be opened by you.  In order to use a\n\
  2379. directory as a buffer's current directory, this predicate must return true.\n\
  2380. A directory name spec may be given instead; then the value is t\n\
  2381. if the directory so specified exists and really is a readable and\n\
  2382. searchable directory.")
  2383.   (filename)
  2384.      Lisp_Object filename;
  2385. {
  2386.   /* This function can GC */
  2387.   Lisp_Object handler;
  2388.   struct gcpro gcpro1;
  2389.  
  2390.   /* If the file name has special constructs in it,
  2391.      call the corresponding file handler.  */
  2392.   handler = Ffind_file_name_handler (filename, Qfile_accessible_directory_p);
  2393.   if (!NILP (handler))
  2394.     return call2 (handler, Qfile_accessible_directory_p,
  2395.           filename);
  2396.  
  2397.   GCPRO1 (filename);
  2398.   if (NILP (Ffile_directory_p (filename)))
  2399.     {
  2400.       UNGCPRO;
  2401.       return (Qnil);
  2402.     }
  2403.   handler = Ffile_executable_p (filename);
  2404.   UNGCPRO;
  2405.   return (handler);
  2406. }
  2407.  
  2408. DEFUN ("file-modes", Ffile_modes, Sfile_modes, 1, 1, 0,
  2409.   "Return mode bits of FILE, as an integer.")
  2410.   (filename)
  2411.      Lisp_Object filename;
  2412. {
  2413.   /* This function can GC */
  2414.   Lisp_Object abspath;
  2415.   struct stat st;
  2416.   Lisp_Object handler;
  2417.   struct gcpro gcpro1;
  2418.   
  2419.   GCPRO1 (filename);
  2420.   abspath = expand_and_dir_to_file (filename,
  2421.                     current_buffer->directory);
  2422.   UNGCPRO;
  2423.  
  2424.   /* If the file name has special constructs in it,
  2425.      call the corresponding file handler.  */
  2426.   GCPRO1 (abspath);
  2427.   handler = Ffind_file_name_handler (abspath, Qfile_modes);
  2428.   UNGCPRO;
  2429.   if (!NILP (handler))
  2430.     return call2 (handler, Qfile_modes, abspath);
  2431.  
  2432.   if (stat ((char *) string_data (XSTRING (abspath)), &st) < 0)
  2433.     return Qnil;
  2434.  
  2435. #ifdef MSDOS
  2436.   {
  2437.     /* #### This code is duplicated in dired.c */
  2438.     int len;
  2439.     char *suffix;
  2440.     if (S_ISREG (st.st_mode)
  2441.     && (len = string_length (XSTRING (abspath))) >= 5
  2442.     && (stricmp ((suffix = string_data (XSTRING (abspath)) + len-4), ".com") == 0
  2443.         || stricmp (suffix, ".exe") == 0
  2444.         || stricmp (suffix, ".bat") == 0))
  2445.       st.st_mode |= S_IEXEC;
  2446.   }
  2447. #endif /* MSDOS */
  2448.  
  2449.   return make_number (st.st_mode & 07777);
  2450. }
  2451.  
  2452. DEFUN ("set-file-modes", Fset_file_modes, Sset_file_modes, 2, 2, 0,
  2453.   "Set mode bits of FILE to MODE (an integer).\n\
  2454. Only the 12 low bits of MODE are used.")
  2455.   (filename, mode)
  2456.      Lisp_Object filename, mode;
  2457. {
  2458.   /* This function can GC */
  2459.   Lisp_Object abspath;
  2460.   Lisp_Object handler;
  2461.   struct gcpro gcpro1, gcpro2;
  2462.   
  2463.   GCPRO2 (filename, mode);
  2464.   abspath = Fexpand_file_name (filename, current_buffer->directory);
  2465.   CHECK_INT (mode, 1);
  2466.   UNGCPRO;
  2467.  
  2468.   /* If the file name has special constructs in it,
  2469.      call the corresponding file handler.  */
  2470.   GCPRO1 (abspath);
  2471.   handler = Ffind_file_name_handler (abspath, Qset_file_modes);
  2472.   UNGCPRO;
  2473.   if (!NILP (handler))
  2474.     return call3 (handler, Qset_file_modes, abspath, mode);
  2475.  
  2476. #ifndef APOLLO
  2477.   if (chmod ((char *) string_data (XSTRING (abspath)), XINT (mode)) < 0)
  2478.     report_file_error ("Doing chmod", Fcons (abspath, Qnil));
  2479. #else /* APOLLO */
  2480.   if (!egetenv ("USE_DOMAIN_ACLS"))
  2481.     {
  2482.       struct stat st;
  2483.  
  2484.       /* chmod on apollo also change the file's modtime; need to save the
  2485.      modtime and then restore it. */
  2486.       if (stat ((char *) string_data (XSTRING (abspath)), &st) < 0)
  2487.     {
  2488.       report_file_error ("Doing chmod", Fcons (abspath, Qnil));
  2489.       return (Qnil);
  2490.     }
  2491.  
  2492.       if (chmod ((char *) string_data (XSTRING (abspath)), XINT (mode)) < 0)
  2493.      report_file_error ("Doing chmod", Fcons (abspath, Qnil));
  2494.  
  2495.       /* reset the old accessed and modified times.  */
  2496.       {
  2497.         EMACS_TIME atime, mtime;
  2498.     /* +1 due to an Apollo roundoff bug */
  2499.     EMACS_SET_SECS_USECS (atime, st.st_atime + 1, 0);
  2500.         /* +1 due to an Apollo roundoff bug */
  2501.     EMACS_SET_SECS_USECS (mtime, st.st_mtime + 1, 0);
  2502.         set_file_times ((char *) string_data (XSTRING (abspath)), atime,
  2503.             mtime);
  2504.       }
  2505.  
  2506. #endif /* APOLLO */
  2507.  
  2508.   return Qnil;
  2509. }
  2510.  
  2511. DEFUN ("set-default-file-modes", Fset_default_file_modes,
  2512.        Sset_default_file_modes, 1, 1, 0,
  2513.     "Set the file permission bits for newly created files.\n\
  2514. MASK should be an integer; if a permission's bit in MASK is 1,\n\
  2515. subsequently created files will not have that permission enabled.\n\
  2516. Only the low 9 bits are used.\n\
  2517. This setting is inherited by subprocesses.")
  2518.   (mode)
  2519.      Lisp_Object mode;
  2520. {
  2521.   CHECK_INT (mode, 0);
  2522.   
  2523.   umask ((~ XINT (mode)) & 0777);
  2524.  
  2525.   return Qnil;
  2526. }
  2527.  
  2528. DEFUN ("default-file-modes", Fdefault_file_modes, Sdefault_file_modes, 0, 0, 0,
  2529.     "Return the default file protection for created files.\n\
  2530. The umask value determines which permissions are enabled in newly\n\
  2531. created files.  If a permission's bit in the umask is 1, subsequently\n\
  2532. created files will not have that permission enabled.")
  2533.   ()
  2534. {
  2535.   int mode;
  2536.  
  2537.   mode = umask (0);
  2538.   umask (mode);
  2539.  
  2540.   return make_number ((~ mode) & 0777);
  2541. }
  2542.  
  2543. #ifndef VMS
  2544. DEFUN ("unix-sync", Funix_sync, Sunix_sync, 0, 0, "",
  2545.   "Tell Unix to finish all pending disk updates.")
  2546.   ()
  2547. {
  2548.   sync ();
  2549.   return Qnil;
  2550. }
  2551. #endif /* !VMS */
  2552.  
  2553.  
  2554. DEFUN ("file-newer-than-file-p", Ffile_newer_than_file_p,
  2555.        Sfile_newer_than_file_p, 2, 2, 0,
  2556.   "Return t if file FILE1 is newer than file FILE2.\n\
  2557. If FILE1 does not exist, the answer is nil;\n\
  2558. otherwise, if FILE2 does not exist, the answer is t.")
  2559.   (file1, file2)
  2560.      Lisp_Object file1, file2;
  2561. {
  2562.   /* This function can GC */
  2563.   Lisp_Object abspath1, abspath2;
  2564.   struct stat st;
  2565.   int mtime1;
  2566.   Lisp_Object handler;
  2567.   struct gcpro gcpro1, gcpro2;
  2568.  
  2569.   CHECK_STRING (file1, 0);
  2570.   CHECK_STRING (file2, 0);
  2571.  
  2572.   abspath1 = Qnil;
  2573.   GCPRO2 (abspath1, file2);
  2574.   abspath1 = expand_and_dir_to_file (file1,
  2575.                      current_buffer->directory);
  2576.   abspath2 = expand_and_dir_to_file (file2,
  2577.                      current_buffer->directory);
  2578.   UNGCPRO;
  2579.  
  2580.   /* If the file name has special constructs in it,
  2581.      call the corresponding file handler.  */
  2582.   GCPRO2 (abspath1, abspath2);
  2583.   handler = Ffind_file_name_handler (abspath1, Qfile_newer_than_file_p);
  2584.   if (NILP (handler))
  2585.     handler = Ffind_file_name_handler (abspath2, Qfile_newer_than_file_p);
  2586.   UNGCPRO;
  2587.   if (!NILP (handler))
  2588.     return call3 (handler, Qfile_newer_than_file_p, abspath1,
  2589.           abspath2);
  2590.  
  2591.   if (stat ((char *) string_data (XSTRING (abspath1)), &st) < 0)
  2592.     return Qnil;
  2593.  
  2594.   mtime1 = st.st_mtime;
  2595.  
  2596.   if (stat ((char *) string_data (XSTRING (abspath2)), &st) < 0)
  2597.     return Qt;
  2598.  
  2599.   return (mtime1 > st.st_mtime) ? Qt : Qnil;
  2600. }
  2601.  
  2602.  
  2603. DEFUN ("compute-buffer-file-truename", Fcompute_buffer_file_truename,
  2604.        Scompute_buffer_file_truename, 0, 0, 0,
  2605.   "Recomputes this buffer's value of `buffer-file-truename'\n\
  2606. based on the current value of `buffer-file-name'.")
  2607.        ()
  2608. {
  2609.   /* This function can GC */
  2610.   Lisp_Object fn, dn;
  2611.  
  2612.   if (NILP (current_buffer->filename))
  2613.   {
  2614.     current_buffer->truename = Qnil;
  2615.     return (Qnil);
  2616.   }
  2617.  
  2618.   fn = Ffile_truename (current_buffer->filename, Qnil);
  2619.   if (NILP (fn))
  2620.     {
  2621.       struct gcpro gcpro1;
  2622.  
  2623.       /* If the file name is resolvable, we're done.  Otherwise, the file
  2624.      probably doesn't exist yet.  First, resolve the file's directory...
  2625.        */
  2626.       dn = Ffile_name_directory (current_buffer->filename);
  2627.       GCPRO1 (dn);
  2628.       fn = Ffile_truename (dn, Qnil);
  2629.       if (! NILP (fn))
  2630.         dn = fn;
  2631.       
  2632.       /* ...and then expand the file relative to that. */
  2633.       fn = Fexpand_file_name
  2634.          (Ffile_name_nondirectory (current_buffer->filename),
  2635.           dn);
  2636.       UNGCPRO;
  2637.     }
  2638.   current_buffer->truename = fn;
  2639.  
  2640.   if (find_file_use_truenames)
  2641.     {
  2642.       struct gcpro gcpro1;
  2643.       GCPRO1 (fn);
  2644.       current_buffer->filename = fn;
  2645.       current_buffer->directory = Ffile_name_directory (fn);
  2646.       UNGCPRO;
  2647.     }
  2648.   return fn;
  2649. }
  2650.  
  2651.  
  2652.  
  2653. #ifdef MSDOS
  2654. Lisp_Object Qfind_buffer_file_type;
  2655. #endif
  2656.  
  2657. #define READ_BUF_SIZE (2 << 16)
  2658.  
  2659. DEFUN ("insert-file-contents-internal", Finsert_file_contents_internal,
  2660.        Sinsert_file_contents_internal, 1, 5, 0,
  2661.   "Insert contents of file FILENAME after point.\n\
  2662. Returns list of absolute file name and length of data inserted.\n\
  2663. If second argument VISIT is non-nil, the buffer's visited filename\n\
  2664. and last save file modtime are set, and it is marked unmodified.\n\
  2665. If visiting and the file does not exist, visiting is completed\n\
  2666. before the error is signaled.\n\n\
  2667. The optional third and fourth arguments BEG and END\n\
  2668. specify what portion of the file to insert.\n\
  2669. If VISIT is non-nil, BEG and END must be nil.\n\
  2670. If optional fifth argument REPLACE is non-nil,\n\
  2671. it means replace the current buffer contents (in the accessible portion)\n\
  2672. with the file contents.  This is better than simply deleting and inserting\n\
  2673. the whole thing because (1) it preserves some marker positions\n\
  2674. and (2) it puts less data in the undo list.\n\
  2675. If support for Mule exists in this Emacs, code conversion occurs according\n\
  2676. to the value of `input-coding-system', and `used-coding-system' is set to\n\
  2677. the coding system actually used.  Currently BEG and END refer to byte\n\
  2678. positions (as opposed to character positions), even in Mule.")
  2679.   (filename, visit, beg, end, replace)
  2680.      Lisp_Object filename, visit, beg, end, replace;
  2681. {
  2682.   /* This function can GC */
  2683.   struct stat st;
  2684.   int fd;
  2685.   int saverrno = 0;
  2686.   int inserted = 0;
  2687.   int speccount;
  2688.   struct gcpro gcpro1, gcpro2, gcpro3;
  2689.   Lisp_Object handler, val;
  2690.   int total;
  2691.   Bufbyte read_buf[READ_BUF_SIZE];
  2692.   int mc_count;
  2693.   struct buffer *buf = current_buffer;
  2694.  
  2695.   val = Qnil;
  2696.  
  2697.   GCPRO3 (filename, val, visit);
  2698.   if (!NILP (replace))
  2699.     mc_count = begin_multiple_change (buf,
  2700.                       BUF_BEG (buf),
  2701.                       BUF_Z (buf));
  2702.   else
  2703.     mc_count = begin_multiple_change (buf, BUF_PT (buf), BUF_PT (buf));
  2704.  
  2705.   speccount = specpdl_depth (); /* begin_multiple_change also adds
  2706.                    an unwind_protect */
  2707.  
  2708.   filename = Fexpand_file_name (filename, Qnil);
  2709.  
  2710.   /* If the file name has special constructs in it,
  2711.      call the corresponding file handler.  */
  2712.   handler = Ffind_file_name_handler (filename, Qinsert_file_contents);
  2713.   if (!NILP (handler))
  2714.     {
  2715.       val = call6 (handler, Qinsert_file_contents, filename,
  2716.                    visit, beg, end, replace);
  2717.       goto handled;
  2718.     }
  2719.  
  2720.   if (!NILP (beg) || !NILP (end))
  2721.     if (!NILP (visit))
  2722.       error ("Attempt to visit less than an entire file");
  2723.  
  2724.   if (!NILP (beg))
  2725.     CHECK_INT (beg, 0);
  2726.   else
  2727.     beg = Qzero;
  2728.  
  2729.   if (!NILP (end))
  2730.     CHECK_INT (end, 0);
  2731.  
  2732.   fd = -1;
  2733.  
  2734. #ifndef APOLLO
  2735.   if (stat ((char *) string_data (XSTRING (filename)), &st) < 0)
  2736. #else /* APOLLO */
  2737.   if ((fd = open ((char *) string_data (XSTRING (filename)), O_RDONLY, 0)) < 0
  2738.       || fstat (fd, &st) < 0)
  2739. #endif /* APOLLO */
  2740.     {
  2741.       if (fd >= 0) close (fd);
  2742.     badopen:
  2743.       if (NILP (visit))
  2744.     report_file_error ("Opening input file",
  2745.                Fcons (filename, Qnil));
  2746.       st.st_mtime = -1;
  2747.       goto notfound;
  2748.     }
  2749.  
  2750. #ifdef S_IFREG
  2751.   /* This code will need to be changed in order to work on named
  2752.      pipes, and it's probably just not worth it.  So we should at
  2753.      least signal an error.  */
  2754.   if (!S_ISREG (st.st_mode))
  2755.     {
  2756.       end_multiple_change (buf, mc_count);
  2757.       return Fsignal (Qfile_error,
  2758.               list2 (build_translated_string ("not a regular file"),
  2759.                  filename));
  2760.     }
  2761. #endif
  2762.  
  2763.   if (fd < 0)
  2764.     if ((fd = open ((char *) string_data (XSTRING (filename)), O_RDONLY, 0)) < 0)
  2765.       goto badopen;
  2766.  
  2767.   /* Replacement should preserve point as it preserves markers.  */
  2768.   if (!NILP (replace))
  2769.     record_unwind_protect (restore_point_unwind, Fpoint_marker (Qnil, Qnil));
  2770.  
  2771.   record_unwind_protect (close_file_unwind, make_number (fd));
  2772.  
  2773.   /* Supposedly happens on VMS.  */
  2774.   if (st.st_size < 0)
  2775.     error ("File size is negative");
  2776.  
  2777.   if (NILP (end))
  2778.     {
  2779.       end = make_number (st.st_size);
  2780.       if (XINT (end) != st.st_size)
  2781.     error ("maximum buffer size exceeded");
  2782.     }
  2783.  
  2784.   /* If requested, replace the accessible part of the buffer
  2785.      with the file contents.  Avoid replacing text at the
  2786.      beginning or end of the buffer that matches the file contents;
  2787.      that preserves markers pointing to the unchanged parts.  */
  2788. #if !defined (MSDOS) && !defined (MULE)
  2789.   /* The replace-mode code currently only works when the assumption
  2790.      'one byte == one char' holds true.  This fails under MSDOS
  2791.      (because newlines are represented as CR-LF in text files)
  2792.      and under Mule and I18N4 because files may contain multibyte
  2793.      characters. */
  2794. # define FSFMACS_SPEEDY_INSERT
  2795. #endif
  2796. #ifndef FSFMACS_SPEEDY_INSERT
  2797.   if (!NILP (replace))
  2798.     {
  2799.       buffer_delete_range (buf, BUF_BEG (buf), BUF_Z (buf),
  2800.                !NILP (visit) ? INSDEL_NO_LOCKING : 0);
  2801.     }
  2802. #else /* FSFMACS_SPEEDY_INSERT */
  2803.   if (!NILP (replace))
  2804.     {
  2805.       char buffer[1 << 14];
  2806.       Bufpos same_at_start = BUF_BEGV (buf);
  2807.       Bufpos same_at_end = BUF_ZV (buf);
  2808.       int overlap;
  2809.  
  2810.       /* Count how many chars at the start of the file
  2811.      match the text at the beginning of the buffer.  */
  2812.       while (1)
  2813.     {
  2814.       int nread;
  2815.       Bufpos bufpos;
  2816.  
  2817.       nread = read_allowing_quit (fd, buffer, sizeof buffer);
  2818.       if (nread < 0)
  2819.         error ("IO error reading %s: %s",
  2820.            string_data (XSTRING (filename)), strerror (errno));
  2821.       else if (nread == 0)
  2822.         break;
  2823.       bufpos = 0;
  2824.       while (bufpos < nread && same_at_start < BUF_ZV (buf)
  2825.          && BUF_FETCH_CHAR (buf, same_at_start) == buffer[bufpos])
  2826.         same_at_start++, bufpos++;
  2827.       /* If we found a discrepancy, stop the scan.
  2828.          Otherwise loop around and scan the next bufferfull.  */
  2829.       if (bufpos != nread)
  2830.         break;
  2831.     }
  2832.       /* If the file matches the buffer completely,
  2833.      there's no need to replace anything.  */
  2834.       if (same_at_start - BUF_BEGV (buf) == st.st_size)
  2835.     {
  2836.       close (fd);
  2837.           unbind_to (speccount, Qnil);
  2838.       /* Truncate the buffer to the size of the file.  */
  2839.       buffer_delete_range (buf, same_at_start, same_at_end,
  2840.                    !NILP (visit) ? INSDEL_NO_LOCKING : 0);
  2841.       goto handled;
  2842.     }
  2843.       /* Count how many chars at the end of the file
  2844.      match the text at the end of the buffer.  */
  2845.       while (1)
  2846.     {
  2847.       int total_read, nread;
  2848.       Bufpos bufpos, curpos, trial;
  2849.  
  2850.       /* At what file position are we now scanning?  */
  2851.       curpos = st.st_size - (BUF_ZV (buf) - same_at_end);
  2852.       /* If the entire file matches the buffer tail, stop the scan.  */
  2853.       if (curpos == 0)
  2854.         break;
  2855.       /* How much can we scan in the next step?  */
  2856.       trial = min (curpos, sizeof buffer);
  2857.       if (lseek (fd, curpos - trial, 0) < 0)
  2858.         report_file_error ("Setting file position",
  2859.                    Fcons (filename, Qnil));
  2860.  
  2861.       total_read = 0;
  2862.       while (total_read < trial)
  2863.         {
  2864.           nread = read_allowing_quit (fd, buffer + total_read,
  2865.                       trial - total_read);
  2866.           if (nread <= 0)
  2867.         error ("IO error reading %s: %s",
  2868.                string_data (XSTRING (filename)), strerror (errno));
  2869.           total_read += nread;
  2870.         }
  2871.       /* Scan this bufferfull from the end, comparing with
  2872.          the Emacs buffer.  */
  2873.       bufpos = total_read;
  2874.       /* Compare with same_at_start to avoid counting some buffer text
  2875.          as matching both at the file's beginning and at the end.  */
  2876.       while (bufpos > 0 && same_at_end > same_at_start
  2877.          && BUF_FETCH_CHAR (buf, same_at_end - 1) ==
  2878.          buffer[bufpos - 1])
  2879.         same_at_end--, bufpos--;
  2880.       /* If we found a discrepancy, stop the scan.
  2881.          Otherwise loop around and scan the preceding bufferfull.  */
  2882.       if (bufpos != 0)
  2883.         break;
  2884.     }
  2885.  
  2886.       /* Don't try to reuse the same piece of text twice.  */
  2887.       overlap = same_at_start - BUF_BEGV (buf) -
  2888.     (same_at_end + st.st_size - BUF_ZV (buf));
  2889.       if (overlap > 0)
  2890.     same_at_end += overlap;
  2891.  
  2892.       /* Arrange to read only the nonmatching middle part of the file.  */
  2893.       beg = make_number (same_at_start - BUF_BEGV (buf));
  2894.       end = make_number (st.st_size - (BUF_ZV (buf) - same_at_end));
  2895.  
  2896.       buffer_delete_range (buf, same_at_start, same_at_end,
  2897.                !NILP (visit) ? INSDEL_NO_LOCKING : 0);
  2898.       /* Insert from the file at the proper position.  */
  2899.       BUF_SET_PT (buf, same_at_start);
  2900.     }
  2901. #endif /* FSFMACS_SPEEDY_INSERT */
  2902.  
  2903.   total = XINT (end) - XINT (beg);
  2904.  
  2905.   if (XINT (beg) != 0
  2906. #ifdef FSFMACS_SPEEDY_INSERT
  2907.       /* why was this here? asked jwz.  The reason is that the replace-mode
  2908.      connivings above will normally put the file pointer other than
  2909.      where it should be. */
  2910.       || !NILP (replace)
  2911. #endif /* !FSFMACS_SPEEDY_INSERT */
  2912.       )
  2913.     {
  2914.       if (lseek (fd, XINT (beg), 0) < 0)
  2915.     report_file_error ("Setting file position",
  2916.                Fcons (filename, Qnil));
  2917.     }
  2918.  
  2919.   {
  2920.     Bufpos cur_point = BUF_PT (buf);
  2921.     struct gcpro gcpro1;
  2922.     Lisp_Object stream_obj = make_filedesc_stream (fd, LSTR_ALLOW_QUIT);
  2923.     Lstream *stream = XLSTREAM (stream_obj);
  2924.  
  2925.     Lstream_set_buffering (stream, LSTREAM_BLOCKN_BUFFERED, 65536);
  2926. #ifdef MULE
  2927.     stream = make_mule_encoding_stream (stream, mccode);
  2928. #endif
  2929.  
  2930.     XSETLSTREAM (stream_obj, stream);
  2931.     GCPRO1 (stream_obj);
  2932.     while (inserted < total)
  2933.       {
  2934.     int try_count = min (total - inserted, READ_BUF_SIZE);
  2935.     int this_len;
  2936.  
  2937.     QUIT;
  2938.     this_len = Lstream_read (stream, read_buf, try_count);
  2939.       
  2940.     if (this_len <= 0)
  2941.       {
  2942.         if (this_len < 0)
  2943.           saverrno = errno;
  2944.         break;
  2945.       }
  2946.  
  2947.     buffer_insert_raw_string_1 (buf, cur_point, read_buf, this_len,
  2948.                     !NILP (visit) ? INSDEL_NO_LOCKING : 0);
  2949.     inserted += this_len;
  2950.     cur_point += this_len;
  2951.       }
  2952.     Lstream_close (stream);
  2953.     UNGCPRO;
  2954.   }
  2955.  
  2956. #ifdef MSDOS
  2957.   /* Determine file type from name and remove LFs from CR-LFs if the file
  2958.      is deemed to be a text file.  */
  2959.   {
  2960.     struct gcpro gcpro1;
  2961.     GCPRO1 (filename);
  2962.     buf->buffer_file_type
  2963.       = call1_in_buffer (buf, Qfind_buffer_file_type, filename);
  2964.     UNGCPRO;
  2965.     if (NILP (buf->buffer_file_type))
  2966.       {
  2967.     buffer_do_msdos_crlf_to_lf (buf, ####);
  2968.       }
  2969.   }
  2970. #endif
  2971.  
  2972.   /* Close the file */
  2973.   unbind_to (speccount, Qnil);
  2974.  
  2975.   if (saverrno != 0)
  2976.     {
  2977.       error ("IO error reading %s: %s",
  2978.          string_data (XSTRING (filename)), strerror (saverrno));
  2979.     }
  2980.  
  2981.  notfound:
  2982.  handled:
  2983.  
  2984.   end_multiple_change (buf, mc_count);
  2985.  
  2986.   if (!NILP (visit))
  2987.     {
  2988.       if (!EQ (buf->undo_list, Qt))
  2989.     buf->undo_list = Qnil;
  2990. #ifdef APOLLO
  2991.       stat ((char *) string_data (XSTRING (filename)), &st);
  2992. #endif
  2993.       if (NILP (handler))
  2994.     {
  2995.       buf->modtime = st.st_mtime;
  2996.       buf->filename = filename;
  2997.           Fcompute_buffer_file_truename (); /* XEmacs addition */
  2998.     }
  2999.       buf->save_modified = BUF_MODIFF (buf);
  3000.       buf->auto_save_modified = BUF_MODIFF (buf);
  3001.       buf->save_length = make_number (BUF_SIZE (buf));
  3002. #ifdef CLASH_DETECTION
  3003.       if (NILP (handler))
  3004.     {
  3005.       if (!NILP (buf->filename))
  3006.         unlock_file (buf->filename);
  3007.       unlock_file (filename);
  3008.     }
  3009. #endif /* CLASH_DETECTION */
  3010.  
  3011.       /* If visiting nonexistent file, return nil.  */
  3012.       if (buf->modtime == -1)
  3013.     report_file_error ("Opening input file",
  3014.                list1 (filename));
  3015.     }
  3016.  
  3017.   if (inserted > 0)
  3018.     {
  3019.       Lisp_Object p = Vafter_insert_file_functions;
  3020.       struct gcpro gcpro1;
  3021.  
  3022.       GCPRO1 (p);
  3023.       while (!NILP (p))
  3024.     {
  3025.       Lisp_Object insval =
  3026.         call1 (Fcar (p), make_number (inserted));
  3027.       if (!NILP (insval))
  3028.         {
  3029.           CHECK_NATNUM (insval, 0);
  3030.           inserted = XINT (insval);
  3031.         }
  3032.       QUIT;
  3033.       p = Fcdr (p);
  3034.     }
  3035.       UNGCPRO;
  3036.     }
  3037.  
  3038.   UNGCPRO;
  3039.  
  3040.   if (!NILP (val))
  3041.     return (val);
  3042.   else
  3043.     return (list2 (filename, make_number (inserted)));
  3044. }
  3045.  
  3046.  
  3047. static int a_write (Lstream *outstream, Lstream *instream, int pos,
  3048.             Lisp_Object *annot);
  3049. static Lisp_Object build_annotations (Lisp_Object start, Lisp_Object end);
  3050.  
  3051. /* If build_annotations switched buffers, switch back to BUF.
  3052.    Kill the temporary buffer that was selected in the meantime.  */
  3053.  
  3054. static Lisp_Object 
  3055. build_annotations_unwind (Lisp_Object buf)
  3056. {
  3057.   Lisp_Object tembuf;
  3058.  
  3059.   if (XBUFFER (buf) == current_buffer)
  3060.     return Qnil;
  3061.   tembuf = Fcurrent_buffer ();
  3062.   Fset_buffer (buf);
  3063.   Fkill_buffer (tembuf);
  3064.   return Qnil;
  3065. }
  3066.  
  3067. DEFUN ("write-region-internal", Fwrite_region_internal,
  3068.        Swrite_region_internal, 3, 5,
  3069.   "r\nFWrite region to file: ",
  3070.   "Write current region into specified file.\n\
  3071. When called from a program, takes three arguments:\n\
  3072. START, END and FILENAME.  START and END are buffer positions.\n\
  3073. Optional fourth argument APPEND if non-nil means\n\
  3074.   append to existing file contents (if any).\n\
  3075. Optional fifth argument VISIT if t means\n\
  3076.   set the last-save-file-modtime of buffer to this file's modtime\n\
  3077.   and mark buffer not modified.\n\
  3078. If VISIT is a string, it is a second file name;\n\
  3079.   the output goes to FILENAME, but the buffer is marked as visiting VISIT.\n\
  3080.   VISIT is also the file name to lock and unlock for clash detection.\n\
  3081. If VISIT is neither t nor nil nor a string,\n\
  3082.   that means do not print the \"Wrote file\" message.\n\
  3083. Kludgy feature: if START is a string, then that string is written\n\
  3084. to the file, instead of any buffer contents, and END is ignored.\n\
  3085. If support for Mule exists in this Emacs, code conversion occurs according\n\
  3086. to the value of `output-coding-system'.")
  3087.   (start, end, filename, append, visit)
  3088.      Lisp_Object start, end, filename, append, visit;
  3089. {
  3090.   /* This function can GC */
  3091.   int desc;
  3092.   int failure;
  3093.   int save_errno = 0;
  3094.   struct stat st;
  3095.   Lisp_Object fn;
  3096.   int speccount = specpdl_depth ();
  3097. #ifdef VMS
  3098.   Lisp_Object fname = Qnil;  /* If non-nil, original filename (must rename) */
  3099. #endif /* VMS */
  3100.   int visiting_other = STRINGP (visit);
  3101.   int visiting = (EQ (visit, Qt) || visiting_other);
  3102.   int quietly = (!visiting && !NILP (visit));
  3103.   Lisp_Object visit_file = Qnil;
  3104.   Lisp_Object annotations = Qnil;
  3105.   struct buffer *given_buffer;
  3106.   Bufpos start1, end1;
  3107.  
  3108. #ifdef MSDOS
  3109.   int buffer_file_type
  3110.     = NILP (current_buffer->buffer_file_type) ? O_TEXT : O_BINARY;
  3111. #endif
  3112.  
  3113. #ifdef MULE
  3114.   Mule_coding_type *mccode;
  3115.  
  3116.   if (auto_saving)
  3117.     mccode = decode_coding_system (Qnil);
  3118.   else
  3119.     mccode = decode_coding_system (Voutput_coding_system);
  3120. #endif /* MULE */
  3121.  
  3122.   if (!NILP (start) && !STRINGP (start))
  3123.     get_bufrange (current_buffer, start, end, &start1, &end1, 0);
  3124.  
  3125.   {
  3126.     Lisp_Object handler;
  3127.     struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
  3128.     GCPRO4 (start, filename, visit, visit_file);
  3129.  
  3130.     if (visiting_other)
  3131.       visit_file = Fexpand_file_name (visit, Qnil);
  3132.     else
  3133.       visit_file = filename;
  3134.     filename = Fexpand_file_name (filename, Qnil);
  3135.  
  3136.     UNGCPRO;
  3137.  
  3138.     /* If the file name has special constructs in it,
  3139.        call the corresponding file handler.  */
  3140.     handler = Ffind_file_name_handler (filename, Qwrite_region);
  3141.     /* If FILENAME has no handler, see if VISIT has one.  */
  3142.     if (NILP (handler) && STRINGP (visit))
  3143.       handler = Ffind_file_name_handler (visit, Qwrite_region);
  3144.  
  3145.     if (!NILP (handler))
  3146.       {
  3147.         Lisp_Object val = call6 (handler, Qwrite_region, start, end, 
  3148.                                  filename, append, visit);
  3149.     if (visiting)
  3150.       {
  3151.         current_buffer->save_modified = BUF_MODIFF (current_buffer);
  3152.         current_buffer->save_length =
  3153.           make_number (BUF_SIZE (current_buffer));
  3154.         current_buffer->filename = visit_file;
  3155.         MARK_MODELINE_CHANGED;
  3156.       }
  3157.     return val;
  3158.       }
  3159.   }
  3160.  
  3161. #ifdef CLASH_DETECTION
  3162.   if (!auto_saving)
  3163.     {
  3164.       struct gcpro gcpro1, gcpro2, gcpro3;
  3165.       GCPRO3 (start, filename, visit_file);
  3166.       lock_file (visit_file);
  3167.       UNGCPRO;
  3168.     }
  3169. #endif /* CLASH_DETECTION */
  3170.  
  3171.   /* Special kludge to simplify auto-saving.  */
  3172.   if (NILP (start))
  3173.     {
  3174.       start1 = BUF_BEG (current_buffer);
  3175.       end1 = BUF_Z (current_buffer);
  3176.     }
  3177.  
  3178.   record_unwind_protect (build_annotations_unwind, Fcurrent_buffer ());
  3179.  
  3180.   given_buffer = current_buffer;
  3181.   annotations = build_annotations (start, end);
  3182.   if (current_buffer != given_buffer)
  3183.     {
  3184.       start1 = BUF_BEGV (current_buffer);
  3185.       end1 = BUF_ZV (current_buffer);
  3186.     }
  3187.  
  3188.   fn = filename;
  3189.   desc = -1;
  3190.   if (!NILP (append))
  3191. #if defined (MSDOS) || defined (WIN32)
  3192.     desc = open ((char *) string_data (XSTRING (fn)),
  3193.                        (O_WRONLY | buffer_file_type), 0);
  3194. #else
  3195.     desc = open ((char *) string_data (XSTRING (fn)), O_WRONLY, 0);
  3196. #endif
  3197.  
  3198.   if (desc < 0)
  3199. #ifndef VMS
  3200.     {
  3201. #ifdef MSDOS
  3202.       desc = open ((char *) string_data (XSTRING (fn)), 
  3203.                    (O_WRONLY | O_TRUNC | O_CREAT | buffer_file_type), 
  3204.                    (S_IREAD | S_IWRITE));
  3205. #else /* not MSDOS */
  3206.       desc = creat ((char *) string_data (XSTRING (fn)),
  3207.             ((auto_saving) ? auto_save_mode_bits : 0666));
  3208. #endif /* MSDOS */
  3209.     }
  3210. #else /* VMS */
  3211.   {
  3212.     if (auto_saving)    /* Overwrite any previous version of autosave file */
  3213.       {
  3214.     char *fn_data = string_data (XSTRING (fn));
  3215.     /* if fn exists, truncate to zero length */
  3216.     vms_truncate (fn_data);
  3217.     desc = open (fn_data, O_RDWR, 0);
  3218.     if (desc < 0)
  3219.       desc = creat_copy_attrs ((STRINGP (current_buffer->filename)
  3220.                     ? (char *) string_data
  3221.                     (XSTRING (current_buffer->filename))
  3222.                     : 0),
  3223.                    fn_data);
  3224.       }
  3225.     else        /* Write to temporary name and rename if no errors */
  3226.       {
  3227.     Lisp_Object temp_name;
  3228.  
  3229.     struct gcpro gcpro1, gcpro2, gcpro3;
  3230.     GCPRO3 (start, filename, visit_file);
  3231.     {
  3232.       struct gcpro gcpro1, gcpro2, gcpro3; /* Don't have GCPRO6 */
  3233.  
  3234.       GCPRO3 (fn, fname, annotations);
  3235.  
  3236.       temp_name = Ffile_name_directory (filename);
  3237.  
  3238.       if (NILP (temp_name))
  3239.         desc = creat ((char *) string_data (XSTRING (fn)), 0666);
  3240.       else
  3241.         {
  3242.           temp_name =
  3243.         Fmake_temp_name (concat2 (temp_name,
  3244.                       build_string ("$$SAVE$$")));
  3245.           fname = filename;
  3246.           fn = temp_name;
  3247.           desc = creat_copy_attrs (fname,
  3248.                        (char *) string_data (XSTRING (fn)));
  3249.           if (desc < 0)
  3250.         {
  3251.           char *fn_data;
  3252.           /* If we can't open the temporary file, try creating a new
  3253.              version of the original file.  VMS "creat" creates a
  3254.              new version rather than truncating an existing file. */
  3255.           fn = fname;
  3256.           fname = Qnil;
  3257.           fn_data = string_data (XSTRING (fn));
  3258.           desc = creat (fn_data, 0666);
  3259. #if 0                           /* This can clobber an existing file and fail
  3260.                    to replace it, if the user runs out of
  3261.                    space.  */
  3262.           if (desc < 0)
  3263.             {
  3264.               /* We can't make a new version;
  3265.              try to truncate and rewrite existing version if any.
  3266.                */
  3267.               vms_truncate (fn_data);
  3268.               desc = open (fn_data, O_RDWR, 0);
  3269.             }
  3270. #endif
  3271.         }
  3272.         }
  3273.       UNGCPRO;
  3274.     }
  3275.     UNGCPRO;
  3276.       }
  3277.   }
  3278. #endif /* VMS */
  3279.  
  3280.   if (desc < 0)
  3281.     {
  3282. #ifdef CLASH_DETECTION
  3283.       save_errno = errno;
  3284.       if (!auto_saving) unlock_file (visit_file);
  3285.       errno = save_errno;
  3286. #endif /* CLASH_DETECTION */
  3287.       report_file_error ("Opening output file",
  3288.              Fcons (filename, Qnil));
  3289.     }
  3290.  
  3291.   {
  3292.     Lisp_Object desc_locative = Fcons (make_number (desc), Qnil);
  3293.     Lisp_Object instream_obj = Qnil, outstream_obj = Qnil;
  3294.     Lstream *instream, *outstream;
  3295.     struct gcpro gcpro1, gcpro2;
  3296.     /* need to gcpro; QUIT could happen out of call to write() */
  3297.     GCPRO2 (instream_obj, outstream_obj);
  3298.  
  3299.     record_unwind_protect (close_file_unwind, desc_locative);
  3300.  
  3301.     if (!NILP (append))
  3302.       {
  3303.     if (lseek (desc, 0, 2) < 0)
  3304.       {
  3305. #ifdef CLASH_DETECTION
  3306.         if (!auto_saving) unlock_file (visit_file);
  3307. #endif /* CLASH_DETECTION */
  3308.         report_file_error ("Lseek error",
  3309.                    list1 (filename));
  3310.       }
  3311.       }
  3312.  
  3313. #ifdef VMS
  3314. /*
  3315.  * Kludge Warning: The VMS C RTL likes to insert carriage returns
  3316.  * if we do writes that don't end with a carriage return. Furthermore
  3317.  * it cannot handle writes of more then 16K. The modified
  3318.  * version of "sys_write" in SYSDEP.C (see comment there) copes with
  3319.  * this EXCEPT for the last record (iff it doesn't end with a carriage
  3320.  * return). This implies that if your buffer doesn't end with a carriage
  3321.  * return, you get one free... tough. However it also means that if
  3322.  * we make two calls to sys_write (a la the following code) you can
  3323.  * get one at the gap as well. The easiest way to fix this (honest)
  3324.  * is to move the gap to the next newline (or the end of the buffer).
  3325.  * Thus this change.
  3326.  *
  3327.  * Yech!
  3328.  */
  3329.     you lose -- fix this
  3330.     if (GPT > BUF_BEG (current_buffer) && *GPT_ADDR[-1] != '\n')
  3331.       move_gap (find_next_newline (current_buffer, GPT, 1));
  3332. #endif
  3333.  
  3334.     failure = 0;
  3335.  
  3336.     /* Note: I tried increasing the buffering size, along with
  3337.        various other tricks, but nothing seemed to make much of
  3338.        a difference in the time it took to save a large file.
  3339.        (Actually that's not true.  With a local disk, changing
  3340.        the buffer size doesn't seem to make much difference.
  3341.        With an NFS-mounted disk, it could make a lot of difference
  3342.        because you're affecting the number of network requests
  3343.        that need to be made, and there could be a large latency
  3344.        for each request.  So I've increased the buffer size
  3345.        to 64K. */
  3346.     outstream_obj = make_filedesc_stream (desc, 0);
  3347.     Lstream_set_buffering (XLSTREAM (outstream_obj),
  3348.                LSTREAM_BLOCKN_BUFFERED, 65536);
  3349. #ifdef MULE
  3350.     outstream_obj =
  3351.       make_mule_decoding_stream (XLSTREAM (outstream_obj), mccode);
  3352. #endif
  3353.     outstream = XLSTREAM (outstream_obj);
  3354.     if (STRINGP (start))
  3355.       {
  3356.     instream_obj = make_lisp_string_stream (start, 0, -1);
  3357.     start1 = 0;
  3358.       }
  3359.     else
  3360.       instream_obj = make_lisp_buffer_stream (current_buffer, start1, end1,
  3361.                           LSTR_SELECTIVE |
  3362.                           LSTR_IGNORE_ACCESSIBLE);
  3363.     instream = XLSTREAM (instream_obj);
  3364.     failure = (0 > (a_write (outstream, instream, start1, &annotations)));
  3365.     save_errno = errno;
  3366.     /* Note that this doesn't close the desc since we created the
  3367.        stream without the LSTR_CLOSING flag, but it does
  3368.        flush out any buffered data. */
  3369.     if (Lstream_close (outstream) < 0)
  3370.       {
  3371.     failure = 1;
  3372.     save_errno = errno;
  3373.       }
  3374.     Lstream_close (instream);
  3375.     UNGCPRO;
  3376.  
  3377. #ifdef HAVE_FSYNC
  3378.     /* Note fsync appears to change the modtime on BSD4.2 (both vax and sun).
  3379.        Disk full in NFS may be reported here.  */
  3380.     /* mib says that closing the file will try to write as fast as NFS can do
  3381.        it, and that means the fsync here is not crucial for autosave files.  */
  3382.     if (!auto_saving && fsync (desc) < 0)
  3383.       {
  3384.     failure = 1;
  3385.     save_errno = errno;
  3386.       }
  3387. #endif
  3388.  
  3389.     /* Spurious "file has changed on disk" warnings have been 
  3390.        observed on Suns as well.
  3391.        It seems that `close' can change the modtime, under nfs.
  3392.  
  3393.        (This has supposedly been fixed in Sunos 4,
  3394.        but who knows about all the other machines with NFS?)  */
  3395.     /* On VMS and APOLLO, must do the stat after the close
  3396.        since closing changes the modtime.  */
  3397. #if 0 /* !defined (VMS) && !defined (APOLLO) */
  3398.     fstat (desc, &st);
  3399. #endif
  3400.  
  3401.     /* NFS can report a write failure now.  */
  3402.     if (close (desc) < 0)
  3403.       {
  3404.     failure = 1;
  3405.     save_errno = errno;
  3406.       }
  3407.  
  3408.     /* Discard the close unwind-protect.  Execute the one for
  3409.        build_annotations (switches back to the original current buffer
  3410.        as necessary). */
  3411.     XCAR (desc_locative) = Qnil;
  3412.     unbind_to (speccount, Qnil);
  3413.   }
  3414.     
  3415.  
  3416. #ifdef VMS
  3417.   /* If we wrote to a temporary name and had no errors, rename to real name. */
  3418.   if (!NILP (fname))
  3419.     {
  3420.       if (!failure)
  3421.     {
  3422.       failure = (rename ((char *) string_data (XSTRING (fn)), 
  3423.                  (char *) string_data (XSTRING (fname)))
  3424.              != 0);
  3425.       save_errno = errno;
  3426.     }
  3427.       fn = fname;
  3428.     }
  3429. #endif /* VMS */
  3430.  
  3431. #if 1 /* defined (VMS) || defined (APOLLO) */
  3432.   stat ((char *) string_data (XSTRING (fn)), &st);
  3433. #endif
  3434.  
  3435. #ifdef CLASH_DETECTION
  3436.   if (!auto_saving)
  3437.     unlock_file (visit_file);
  3438. #endif /* CLASH_DETECTION */
  3439.  
  3440.   /* Do this before reporting IO error
  3441.      to avoid a "file has changed on disk" warning on
  3442.      next attempt to save.  */
  3443.   if (visiting)
  3444.     current_buffer->modtime = st.st_mtime;
  3445.  
  3446.   if (failure)
  3447.     error ("IO error writing %s: %s", 
  3448.            string_data (XSTRING (fn)), 
  3449.            strerror (save_errno));
  3450.  
  3451.   if (visiting)
  3452.     {
  3453.       current_buffer->save_modified = BUF_MODIFF (current_buffer);
  3454.       current_buffer->save_length = make_number (BUF_SIZE (current_buffer));
  3455.       current_buffer->filename = visit_file;
  3456.       MARK_MODELINE_CHANGED;
  3457.     }
  3458.   else if (quietly)
  3459.     {
  3460.       return Qnil;
  3461.     }
  3462.  
  3463.   if (!auto_saving)
  3464.     {
  3465.       if (visiting_other)
  3466.         message ("Wrote %s", string_data (XSTRING (visit_file)));
  3467.       else
  3468.     {
  3469.       struct gcpro gcpro1;
  3470.       Lisp_Object fsp;
  3471.       GCPRO1 (fn);
  3472.  
  3473.       fsp = Ffile_symlink_p (fn);
  3474.       if (NILP (fsp))
  3475.         message ("Wrote %s", string_data (XSTRING (fn)));
  3476.       else
  3477.         message ("Wrote %s (symlink to %s)", 
  3478.              string_data (XSTRING (fn)), string_data (XSTRING (fsp)));
  3479.       UNGCPRO;
  3480.     }
  3481.     }
  3482.   return Qnil;
  3483. }
  3484.  
  3485. /* #### This is such a load of shit!!!!  There is no way we should define
  3486.    something so stupid as a subr, just sort the fucking list more
  3487.    intelligently. */
  3488. DEFUN ("car-less-than-car", Fcar_less_than_car, Scar_less_than_car, 2, 2, 0,
  3489.   "Return t if (car A) is numerically less than (car B).")
  3490.   (a, b)
  3491.      Lisp_Object a, b;
  3492. {
  3493.   return Flss (Fcar (a), Fcar (b));
  3494. }
  3495.  
  3496. /* Build the complete list of annotations appropriate for writing out
  3497.    the text between START and END, by calling all the functions in
  3498.    write-region-annotate-functions and merging the lists they return.
  3499.    If one of these functions switches to a different buffer, we assume
  3500.    that buffer contains altered text.  Therefore, the caller must
  3501.    make sure to restore the current buffer in all cases,
  3502.    as save-excursion would do.  */
  3503.  
  3504. static Lisp_Object
  3505. build_annotations (Lisp_Object start, Lisp_Object end)
  3506. {
  3507.   /* This function can GC */
  3508.   Lisp_Object annotations;
  3509.   Lisp_Object p, res;
  3510.   struct gcpro gcpro1, gcpro2;
  3511.  
  3512.   annotations = Qnil;
  3513.   p = Vwrite_region_annotate_functions;
  3514.   GCPRO2 (annotations, p);
  3515.   while (!NILP (p))
  3516.     {
  3517.       struct buffer *given_buffer = current_buffer;
  3518.       Vwrite_region_annotations_so_far = annotations;
  3519.       res = call2 (Fcar (p), start, end);
  3520.       /* If the function makes a different buffer current,
  3521.      assume that means this buffer contains altered text to be output.
  3522.      Reset START and END from the buffer bounds
  3523.      and discard all previous annotations because they should have
  3524.      been dealt with by this function.  */
  3525.       if (current_buffer != given_buffer)
  3526.     {
  3527.       start = make_number (BUF_BEGV (current_buffer));
  3528.       end = make_number (BUF_ZV (current_buffer));
  3529.       annotations = Qnil;
  3530.     }
  3531.       (void) Flength (res);     /* Check basic validity of return value */
  3532.       annotations = merge (annotations, res, Qcar_less_than_car);
  3533.       p = Fcdr (p);
  3534.     }
  3535.   UNGCPRO;
  3536.   return annotations;
  3537. }
  3538.  
  3539. /* Write to stream OUTSTREAM the characters from INSTREAM (it is read until
  3540.    EOF is encountered), assuming they start at position POS in the buffer
  3541.    of string that STREAM refers to.  Intersperse with them the annotations
  3542.    from *ANNOT that fall into the range of positions we are reading from,
  3543.    each at its appropriate position.
  3544.  
  3545.    Modify *ANNOT by discarding elements as we output them.
  3546.    The return value is negative in case of system call failure.  */
  3547.  
  3548. /* 4K should probably be fine.  We just need to reduce the number of
  3549.    function calls to reasonable level.  The Lstream stuff itself will
  3550.    batch to 64K to reduce the number of system calls. */
  3551.  
  3552. #define A_WRITE_BATCH_SIZE 4096
  3553.  
  3554. static int
  3555. a_write (Lstream *outstream, Lstream *instream, int pos, Lisp_Object *annot)
  3556. {
  3557.   Lisp_Object tem;
  3558.   int nextpos;
  3559.   unsigned char largebuf[A_WRITE_BATCH_SIZE];
  3560.  
  3561.   while (NILP (*annot) || CONSP (*annot))
  3562.     {
  3563.       tem = Fcar_safe (Fcar (*annot));
  3564.       if (INTP (tem))
  3565.     nextpos = XINT (tem);
  3566.       else
  3567.     nextpos = INT_MAX;
  3568. #ifdef MULE
  3569.       /* If there are annotations left and we have Mule, then we
  3570.      have to do the I/O one emchar at a time so we can
  3571.      determine when to insert the annotation. */
  3572.       if (!NILP (*annot))
  3573.     {
  3574.       Emchar ch;
  3575.       while (pos != nextpos && (ch = Lstream_get_emchar (instream)) != EOF)
  3576.         {
  3577.           if (Lstream_put_emchar (outstream, ch) < 0)
  3578.         return -1;
  3579.           pos++;
  3580.         }
  3581.     }
  3582.       else
  3583. #endif
  3584.     {
  3585.       while (pos != nextpos)
  3586.         {
  3587.           /* Otherwise there is no point to that.  Just go in batches. */
  3588.           int chunk = min (nextpos - pos, A_WRITE_BATCH_SIZE);
  3589.           
  3590.           chunk = Lstream_read (instream, largebuf, chunk);
  3591.           if (chunk < 0)
  3592.         return -1;
  3593.           if (chunk == 0) /* EOF */
  3594.         break;
  3595.           if (Lstream_write (outstream, largebuf, chunk) < chunk)
  3596.         return -1;
  3597.           pos += chunk;
  3598.         }
  3599.     }
  3600.       if (pos == nextpos)
  3601.     {
  3602.       tem = Fcdr (Fcar (*annot));
  3603.       if (STRINGP (tem))
  3604.         {
  3605.           if (Lstream_write (outstream, string_data (XSTRING (tem)),
  3606.                  string_length (XSTRING (tem))) < 0)
  3607.         return -1;
  3608.         }
  3609.       *annot = Fcdr (*annot);
  3610.     }
  3611.       else
  3612.     return 0;
  3613.     }
  3614.   return -1;
  3615. }
  3616.  
  3617.  
  3618.  
  3619. #if 0
  3620. #include <des_crypt.h>
  3621.  
  3622. #define CRYPT_BLOCK_SIZE 8    /* bytes */
  3623. #define CRYPT_KEY_SIZE 8    /* bytes */
  3624.  
  3625. DEFUN ("encrypt-string", Fencrypt_string, Sencrypt_string, 2, 2, 0,
  3626. "Encrypt STRING using KEY.")
  3627.   (string, key)
  3628.      Lisp_Object string, key;
  3629. {
  3630.   char *encrypted_string, *raw_key;
  3631.   int rounded_size, extra, key_size;
  3632.  
  3633.   CHECK_STRING (string, 0);
  3634.   CHECK_STRING (key, 1);
  3635.  
  3636.   extra = string_length (XSTRING (string)) % CRYPT_BLOCK_SIZE;
  3637.   rounded_size = string_length (XSTRING (string)) + extra;
  3638.   encrypted_string = alloca (rounded_size + 1);
  3639.   memcpy (encrypted_string, string_data (XSTRING (string)), string_length (XSTRING (string)));
  3640.   memset (encrypted_string + rounded_size - extra, 0, extra + 1);
  3641.  
  3642.   if (string_length (XSTRING (key)) > CRYPT_KEY_SIZE)
  3643.     key_size = CRYPT_KEY_SIZE;
  3644.   else
  3645.     key_size = string_length (XSTRING (key));
  3646.  
  3647.   raw_key = alloca (CRYPT_KEY_SIZE + 1);
  3648.   memcpy (raw_key, string_data (XSTRING (key)), key_size);
  3649.   memset (raw_key + key_size, 0, (CRYPT_KEY_SIZE + 1) - key_size);
  3650.  
  3651.   (void) ecb_crypt (raw_key, encrypted_string, rounded_size,
  3652.             DES_ENCRYPT | DES_SW);
  3653.   return make_string (encrypted_string, rounded_size);
  3654. }
  3655.  
  3656. DEFUN ("decrypt-string", Fdecrypt_string, Sdecrypt_string, 2, 2, 0,
  3657. "Decrypt STRING using KEY.")
  3658.   (string, key)
  3659.      Lisp_Object string, key;
  3660. {
  3661.   char *decrypted_string, *raw_key;
  3662.   int string_size, key_size;
  3663.  
  3664.   CHECK_STRING (string, 0);
  3665.   CHECK_STRING (key, 1);
  3666.  
  3667.   string_size = string_length (XSTRING (string)) + 1;
  3668.   decrypted_string = alloca (string_size);
  3669.   memcpy (decrypted_string, string_data (XSTRING (string)), string_size);
  3670.   decrypted_string[string_size - 1] = '\0';
  3671.  
  3672.   if (string_length (XSTRING (key)) > CRYPT_KEY_SIZE)
  3673.     key_size = CRYPT_KEY_SIZE;
  3674.   else
  3675.     key_size = string_length (XSTRING (key));
  3676.  
  3677.   raw_key = alloca (CRYPT_KEY_SIZE + 1);
  3678.   memcpy (raw_key, string_data (XSTRING (key)), key_size);
  3679.   memset (raw_key + key_size, 0, (CRYPT_KEY_SIZE + 1) - key_size);
  3680.  
  3681.  
  3682.   (void) ecb_crypt (raw_key, decrypted_string, string_size,
  3683.             DES_DECRYPT | DES_SW);
  3684.   return make_string (decrypted_string, string_size - 1);
  3685. }
  3686. #endif
  3687.  
  3688.  
  3689. DEFUN ("verify-visited-file-modtime", Fverify_visited_file_modtime,
  3690.   Sverify_visited_file_modtime, 1, 1, 0,
  3691.   "Return t if last mod time of BUF's visited file matches what BUF records.\n\
  3692. This means that the file has not been changed since it was visited or saved.")
  3693.   (buf)
  3694.      Lisp_Object buf;
  3695. {
  3696.   /* This function can GC */
  3697.   struct buffer *b;
  3698.   struct stat st;
  3699.   Lisp_Object handler;
  3700.  
  3701.   CHECK_BUFFER (buf, 0);
  3702.   b = XBUFFER (buf);
  3703.  
  3704.   if (!STRINGP (b->filename)) return Qt;
  3705.   if (b->modtime == 0) return Qt;
  3706.  
  3707.   /* If the file name has special constructs in it,
  3708.      call the corresponding file handler.  */
  3709.   handler = Ffind_file_name_handler (b->filename,
  3710.                                      Qverify_visited_file_modtime);
  3711.   if (!NILP (handler))
  3712.     return call2 (handler, Qverify_visited_file_modtime, buf);
  3713.  
  3714.   if (stat ((char *) string_data (XSTRING (b->filename)), &st) < 0)
  3715.     {
  3716.       /* If the file doesn't exist now and didn't exist before,
  3717.      we say that it isn't modified, provided the error is a tame one.  */
  3718.       if (errno == ENOENT || errno == EACCES || errno == ENOTDIR)
  3719.     st.st_mtime = -1;
  3720.       else
  3721.     st.st_mtime = 0;
  3722.     }
  3723.   if (st.st_mtime == b->modtime
  3724.       /* If both are positive, accept them if they are off by one second.  */
  3725.       || (st.st_mtime > 0 && b->modtime > 0
  3726.       && (st.st_mtime == b->modtime + 1
  3727.           || st.st_mtime == b->modtime - 1)))
  3728.     return Qt;
  3729.   return Qnil;
  3730. }
  3731.  
  3732. DEFUN ("clear-visited-file-modtime", Fclear_visited_file_modtime,
  3733.   Sclear_visited_file_modtime, 0, 0, 0,
  3734.   "Clear out records of last mod time of visited file.\n\
  3735. Next attempt to save will certainly not complain of a discrepancy.")
  3736.   ()
  3737. {
  3738.   current_buffer->modtime = 0;
  3739.   return Qnil;
  3740. }
  3741.  
  3742. DEFUN ("visited-file-modtime", Fvisited_file_modtime,
  3743.   Svisited_file_modtime, 0, 0, 0,
  3744.   "Return the current buffer's recorded visited file modification time.\n\
  3745. The value is a list of the form (HIGH . LOW), like the time values\n\
  3746. that `file-attributes' returns.")
  3747.   ()
  3748. {
  3749.   return time_to_lisp ((time_t) current_buffer->modtime);
  3750. }
  3751.  
  3752. DEFUN ("set-visited-file-modtime", Fset_visited_file_modtime,
  3753.   Sset_visited_file_modtime, 0, 1, 0,
  3754.   "Update buffer's recorded modification time from the visited file's time.\n\
  3755. Useful if the buffer was not read from the file normally\n\
  3756. or if the file itself has been changed for some known benign reason.\n\
  3757. An argument specifies the modification time value to use\n\
  3758. (instead of that of the visited file), in the form of a list\n\
  3759. (HIGH . LOW) or (HIGH LOW).")
  3760.   (time_list)
  3761.      Lisp_Object time_list;
  3762. {
  3763.   /* This function can GC */
  3764.   if (!NILP (time_list))
  3765.     {
  3766.       time_t the_time;
  3767.       lisp_to_time (time_list, &the_time);
  3768.       current_buffer->modtime = (int) the_time;
  3769.     }
  3770.   else
  3771.     {
  3772.       Lisp_Object filename;
  3773.       struct stat st;
  3774.       Lisp_Object handler;
  3775.       struct gcpro gcpro1, gcpro2;
  3776.       
  3777.       GCPRO2 (filename, time_list);
  3778.       filename = Fexpand_file_name (current_buffer->filename,
  3779.                     Qnil);
  3780.  
  3781.       /* If the file name has special constructs in it,
  3782.      call the corresponding file handler.  */
  3783.       handler = Ffind_file_name_handler (filename, Qset_visited_file_modtime);
  3784.       UNGCPRO;
  3785.       if (!NILP (handler))
  3786.     /* The handler can find the file name the same way we did.  */
  3787.     return call2 (handler, Qset_visited_file_modtime, Qnil);
  3788.       else if (stat ((char *) string_data (XSTRING (filename)), &st) >= 0)
  3789.     current_buffer->modtime = st.st_mtime;
  3790.     }
  3791.  
  3792.   return Qnil;
  3793. }
  3794.  
  3795. DEFUN ("set-buffer-modtime", Fset_buffer_modtime,
  3796.   Sset_buffer_modtime, 1, 2, 0,
  3797.   "Update BUFFER's recorded modification time from the associated \n\
  3798. file's modtime, if there is an associated file. If not, use the \n\
  3799. current time. In either case, if the optional arg TIME is supplied,\n\
  3800. it will be used if it is either an integer or a cons of two integers.")
  3801.   (buf, in_time)
  3802.   Lisp_Object buf, in_time;
  3803. {
  3804.   /* This function can GC */
  3805.   unsigned long time_to_use = 0;
  3806.   int set_time_to_use = 0;
  3807.   struct stat st;
  3808.  
  3809.   CHECK_BUFFER (buf, 0);
  3810.  
  3811.   if (!NILP (in_time))
  3812.     {
  3813.       if (INTP (in_time))
  3814.         {
  3815.           time_to_use = XINT (in_time);
  3816.           set_time_to_use = 1;
  3817.         }
  3818.       else if ((CONSP (in_time)) &&
  3819.                (INTP (Fcar (in_time))) && 
  3820.                (INTP (Fcdr (in_time))))
  3821.     {
  3822.       time_t the_time;
  3823.       lisp_to_time (in_time, &the_time);
  3824.       time_to_use = (unsigned long) the_time;
  3825.           set_time_to_use = 1;
  3826.         }
  3827.     }
  3828.  
  3829.   if (!set_time_to_use)
  3830.     {
  3831.       Lisp_Object filename = Qnil;
  3832.       struct gcpro gcpro1, gcpro2;
  3833.       GCPRO2 (buf, filename);
  3834.  
  3835.       if (STRINGP (XBUFFER (buf)->filename))
  3836.         filename = Fexpand_file_name (XBUFFER (buf)->filename,
  3837.                       Qnil);
  3838.       else
  3839.         filename = Qnil;
  3840.   
  3841.       UNGCPRO;
  3842.  
  3843.       if (!NILP (filename) && !NILP (Ffile_exists_p (filename)))
  3844.         {
  3845.       Lisp_Object handler;
  3846.  
  3847.       /* If the file name has special constructs in it,
  3848.          call the corresponding file handler.  */
  3849.       GCPRO1 (filename);
  3850.       handler = Ffind_file_name_handler (filename, Qset_buffer_modtime);
  3851.       UNGCPRO;
  3852.       if (!NILP (handler))
  3853.         /* The handler can find the file name the same way we did. */
  3854.         return (call2 (handler, Qset_buffer_modtime, Qnil));
  3855.       else
  3856.         {
  3857.           if (stat ((char *) string_data (XSTRING (filename)), &st) >= 0)
  3858.         time_to_use = st.st_mtime;
  3859.           else
  3860.         time_to_use = time ((time_t *) 0);
  3861.         }
  3862.         }
  3863.       else
  3864.     time_to_use = time ((time_t *) 0);
  3865.     }
  3866.  
  3867.   XBUFFER (buf)->modtime = time_to_use;
  3868.  
  3869.   return Qnil;
  3870. }
  3871.  
  3872.  
  3873. static Lisp_Object
  3874. auto_save_error (Lisp_Object condition_object, Lisp_Object ignored)
  3875. {
  3876.   /* This function can GC */
  3877.   if (gc_in_progress)
  3878.     return Qnil;
  3879.   clear_echo_area (selected_frame (), Qauto_saving, 1);
  3880.   Fding (Qt, Qauto_save_error, Qnil);
  3881.   message ("Auto-saving...error for %s",
  3882.        string_data (XSTRING (current_buffer->name)));
  3883.   Fsleep_for (make_number (1));
  3884.   message ("Auto-saving...error!for %s",
  3885.        string_data (XSTRING (current_buffer->name)));
  3886.   Fsleep_for (make_number (1));
  3887.   message ("Auto-saving...error for %s",
  3888.        string_data (XSTRING (current_buffer->name)));
  3889.   Fsleep_for (make_number (1));
  3890.   return Qnil;
  3891. }
  3892.  
  3893. static Lisp_Object
  3894. auto_save_1 (Lisp_Object ignored)
  3895. {
  3896.   /* This function can GC */
  3897.   struct stat st;
  3898.   Lisp_Object fn = current_buffer->filename;
  3899.   Lisp_Object a = current_buffer->auto_save_file_name;
  3900.  
  3901.   if (!STRINGP (a))
  3902.     return (Qnil);
  3903.  
  3904.   /* Get visited file's mode to become the auto save file's mode.  */
  3905.   if (STRINGP (fn) &&
  3906.       stat ((char *) string_data (XSTRING (fn)), &st) >= 0)
  3907.     /* But make sure we can overwrite it later!  */
  3908.     auto_save_mode_bits = st.st_mode | 0600;
  3909.   else
  3910.     /* default mode for auto-save files of buffers with no file is
  3911.        readable by owner only.  This may annoy some small number of
  3912.        people, but the alternative removes all privacy from email. */
  3913.     auto_save_mode_bits = 0600;
  3914.  
  3915. #ifdef MULE
  3916.   Voutput_coding_system = Qnil;
  3917. #endif
  3918.  
  3919.   return
  3920.     Fwrite_region_internal (Qnil, Qnil, a, Qnil, Qlambda);
  3921. }
  3922.  
  3923.  
  3924. static Lisp_Object
  3925. do_auto_save_unwind (Lisp_Object fd)
  3926. {
  3927.   close (XINT (fd));
  3928.   return (fd);
  3929. }
  3930.  
  3931. /* Fdo_auto_save() checks whether a GC is in progress when it is called,
  3932.    and if so, tries to avoid touching lisp objects.
  3933.  
  3934.    The only time that Fdo_auto_save() is called while GC is in progress
  3935.    is if we're going down, as a result of an abort() or a kill signal.
  3936.    It's fairly important that we generate autosave files in that case!
  3937.  */
  3938.  
  3939. DEFUN ("do-auto-save", Fdo_auto_save, Sdo_auto_save, 0, 2, "",
  3940.   "Auto-save all buffers that need it.\n\
  3941. This is all buffers that have auto-saving enabled\n\
  3942. and are changed since last auto-saved.\n\
  3943. Auto-saving writes the buffer into a file\n\
  3944. so that your editing is not lost if the system crashes.\n\
  3945. This file is not the file you visited; that changes only when you save.\n\
  3946. Normally we run the normal hook `auto-save-hook' before saving.\n\n\
  3947. Non-nil first argument means do not print any message if successful.\n\
  3948. Non-nil second argument means save only current buffer.")
  3949.   (no_message, current_only)
  3950.      Lisp_Object no_message, current_only;
  3951. {
  3952.   /* This function can GC */
  3953.   struct buffer *old = current_buffer, *b;
  3954.   Lisp_Object tail, buf;
  3955.   int auto_saved = 0;
  3956.   int do_handled_files;
  3957.   Lisp_Object oquit = Qnil;
  3958.   int listdesc = -1;
  3959.   int speccount = specpdl_depth ();
  3960.   struct gcpro gcpro1;
  3961.  
  3962.   GCPRO1 (oquit);
  3963.   check_quit (); /* make Vquit_flag accurate */
  3964.   /* Ordinarily don't quit within this function,
  3965.      but don't make it impossible to quit (in case we get hung in I/O).  */
  3966.   oquit = Vquit_flag;
  3967.   Vquit_flag = Qnil;
  3968.  
  3969.   /* No further GCPRO needed, because (when it matters) all Lisp_Object
  3970.      variables point to non-strings reached from Vbuffer_alist.  */
  3971.  
  3972.   auto_saving = 1;
  3973.   if (minibuf_level != 0 || gc_in_progress)
  3974.     no_message = Qt;
  3975.  
  3976.   /* Vrun_hooks is nil before emacs is dumped, and inc-vers.el will
  3977.      eventually call do-auto-save, so don't err here in that case. */
  3978.   if (!NILP (Vrun_hooks) && !gc_in_progress)
  3979.     call1 (Vrun_hooks, Qauto_save_hook);
  3980.  
  3981.   if (STRINGP (Vauto_save_list_file_name))
  3982.     {
  3983. #ifdef MSDOS
  3984.       listdesc = open ((char *) string_data (XSTRING (Vauto_save_list_file_name)), 
  3985.                O_WRONLY | O_TRUNC | O_CREAT | O_TEXT,
  3986.                S_IREAD | S_IWRITE);
  3987. #else /* not MSDOS */
  3988.       listdesc = creat ((char *) string_data (XSTRING (Vauto_save_list_file_name)),
  3989.             0666);
  3990. #endif /* not MSDOS */
  3991.     }
  3992.  
  3993.   /* Arrange to close that file whether or not we get an error.  */
  3994.   if (listdesc >= 0)
  3995.     record_unwind_protect (do_auto_save_unwind, make_number (listdesc));
  3996.  
  3997.   /* First, save all files which don't have handlers.  If Emacs is
  3998.      crashing, the handlers may tweak what is causing Emacs to crash
  3999.      in the first place, and it would be a shame if Emacs failed to
  4000.      autosave perfectly ordinary files because it couldn't handle some
  4001.      ange-ftp'd file.  */
  4002.   for (do_handled_files = 0; do_handled_files < 2; do_handled_files++)
  4003.   {
  4004.     for (tail = Vbuffer_alist;
  4005.          XGCTYPE (tail) == Lisp_Cons;
  4006.          tail = XCDR (tail))
  4007.     {
  4008.       buf = XCDR (XCAR (tail));
  4009.       b = XBUFFER (buf);
  4010.  
  4011.       /* Record all the buffers that have auto save mode
  4012.          in the special file that lists them.  */
  4013.       if (STRINGP (b->auto_save_file_name) && listdesc >= 0
  4014.           && do_handled_files == 0)
  4015.       {
  4016.         write (listdesc,
  4017.            string_ext_data (XSTRING (b->auto_save_file_name)),
  4018.                string_ext_length (XSTRING (b->auto_save_file_name)));
  4019.         write (listdesc, "\n", 1);
  4020.       }
  4021.  
  4022.       if (!NILP (current_only)
  4023.           && b != current_buffer)
  4024.         continue;
  4025.       
  4026.       /* Check for auto save enabled
  4027.          and file changed since last auto save
  4028.          and file changed since last real save.  */
  4029.       if (XGCTYPE (b->auto_save_file_name) == Lisp_String
  4030.       && b->save_modified < BUF_MODIFF (b)
  4031.       && b->auto_save_modified < BUF_MODIFF (b)
  4032.           /* -1 means we've turned off autosaving for a while--see below.  */
  4033.           && XINT (b->save_length) >= 0
  4034.           && (do_handled_files
  4035.               || NILP (Ffind_file_name_handler (b->auto_save_file_name,
  4036.                           Qwrite_region))))
  4037.       {
  4038.         EMACS_TIME before_time, after_time;
  4039.  
  4040.         EMACS_GET_TIME (before_time);
  4041.         /* If we had a failure, don't try again for 20 minutes.  */
  4042.         if (b->auto_save_failure_time >= 0
  4043.             && EMACS_SECS (before_time) - b->auto_save_failure_time < 1200)
  4044.           continue;
  4045.  
  4046.         if (!gc_in_progress &&
  4047.             (XINT (b->save_length) * 10
  4048.              > (BUF_Z (b) - BUF_BEG (b)) * 13)
  4049.             /* A short file is likely to change a large fraction;
  4050.                spare the user annoying messages.  */
  4051.             && XINT (b->save_length) > 5000
  4052.             /* These messages are frequent and annoying for `*mail*'.  */
  4053.             && !EQ (b->filename, Qnil)
  4054.             && NILP (no_message))
  4055.         {
  4056.           /* It has shrunk too much; turn off auto-saving here.
  4057.              Unless we're about to crash, in which case auto-save it
  4058.              anyway.
  4059.              */
  4060.           message ("Buffer %s has shrunk a lot; auto save turned off there",
  4061.                    string_data (XSTRING (b->name)));
  4062.           /* Turn off auto-saving until there's a real save,
  4063.              and prevent any more warnings.  */
  4064.           b->save_length = make_number (-1);
  4065.       if (!gc_in_progress)
  4066.         Fsleep_for (make_number (1));
  4067.           continue;
  4068.         }
  4069.         set_buffer_internal (b);
  4070.         if (!auto_saved && NILP (no_message))
  4071.       {
  4072.         char *msg = "Auto-saving...";
  4073.         echo_area_message (selected_frame (), (unsigned char *) msg, Qnil,
  4074.                    0, strlen (msg), Qauto_saving);
  4075.       }
  4076.         condition_case_1 (Qt,
  4077.                           auto_save_1, Qnil,
  4078.                           auto_save_error, Qnil);
  4079.         auto_saved++;
  4080.         b->auto_save_modified = BUF_MODIFF (b);
  4081.         b->save_length = make_number (BUF_SIZE (b));
  4082.         set_buffer_internal (old);
  4083.  
  4084.         EMACS_GET_TIME (after_time);
  4085.         /* If auto-save took more than 60 seconds,
  4086.            assume it was an NFS failure that got a timeout.  */
  4087.         if (EMACS_SECS (after_time) - EMACS_SECS (before_time) > 60)
  4088.           b->auto_save_failure_time = EMACS_SECS (after_time);
  4089.       }
  4090.     }
  4091.   }
  4092.  
  4093.   /* Prevent another auto save till enough input events come in.  */
  4094.   if (auto_saved)
  4095.     record_auto_save ();
  4096.  
  4097.   /* Show "...done" only if the echo area would otherwise be empty. */
  4098.   if (auto_saved && NILP (no_message)
  4099.       && NILP (clear_echo_area (selected_frame (), Qauto_saving, 0)))
  4100.     {
  4101.       char *msg = "Auto-saving...done";
  4102.       echo_area_message (selected_frame (), (unsigned char *) msg, Qnil,
  4103.              0, strlen (msg), Qauto_saving);
  4104.     }
  4105.  
  4106.   Vquit_flag = oquit;
  4107.  
  4108.   auto_saving = 0;
  4109.   RETURN_UNGCPRO (unbind_to (speccount, Qnil));
  4110. }
  4111.  
  4112. DEFUN ("set-buffer-auto-saved", Fset_buffer_auto_saved,
  4113.   Sset_buffer_auto_saved, 0, 0, 0,
  4114.   "Mark current buffer as auto-saved with its current text.\n\
  4115. No auto-save file will be written until the buffer changes again.")
  4116.   ()
  4117. {
  4118.   current_buffer->auto_save_modified = BUF_MODIFF (current_buffer);
  4119.   current_buffer->save_length = make_number (BUF_SIZE (current_buffer));
  4120.   current_buffer->auto_save_failure_time = -1;
  4121.   return Qnil;
  4122. }
  4123.  
  4124. DEFUN ("clear-buffer-auto-save-failure", Fclear_buffer_auto_save_failure,
  4125.   Sclear_buffer_auto_save_failure, 0, 0, 0,
  4126.   "Clear any record of a recent auto-save failure in the current buffer.")
  4127.   ()
  4128. {
  4129.   current_buffer->auto_save_failure_time = -1;
  4130.   return Qnil;
  4131. }
  4132.  
  4133. DEFUN ("recent-auto-save-p", Frecent_auto_save_p, Srecent_auto_save_p,
  4134.   0, 0, 0,
  4135.   "Return t if buffer has been auto-saved since last read in or saved.")
  4136.   ()
  4137. {
  4138.   return (current_buffer->save_modified <
  4139.       current_buffer->auto_save_modified) ? Qt : Qnil;
  4140. }
  4141.  
  4142.  
  4143. /************************************************************************/
  4144. /*                            initialization                            */
  4145. /************************************************************************/
  4146.  
  4147. void
  4148. syms_of_fileio (void)
  4149. {
  4150.   defsymbol (&Qexpand_file_name, "expand-file-name");
  4151.   defsymbol (&Qfile_truename, "file-truename");
  4152.   defsymbol (&Qsubstitute_in_file_name, "substitute-in-file-name");
  4153.   defsymbol (&Qdirectory_file_name, "directory-file-name");
  4154.   defsymbol (&Qfile_name_directory, "file-name-directory");
  4155.   defsymbol (&Qfile_name_nondirectory, "file-name-nondirectory");
  4156.   defsymbol (&Qunhandled_file_name_directory, "unhandled-file-name-directory");
  4157.   defsymbol (&Qfile_name_as_directory, "file-name-as-directory");
  4158.   defsymbol (&Qcopy_file, "copy-file");
  4159.   defsymbol (&Qmake_directory_internal, "make-directory-internal");
  4160.   defsymbol (&Qdelete_directory, "delete-directory");
  4161.   defsymbol (&Qdelete_file, "delete-file");
  4162.   defsymbol (&Qrename_file, "rename-file");
  4163.   defsymbol (&Qadd_name_to_file, "add-name-to-file");
  4164.   defsymbol (&Qmake_symbolic_link, "make-symbolic-link");
  4165.   defsymbol (&Qfile_exists_p, "file-exists-p");
  4166.   defsymbol (&Qfile_executable_p, "file-executable-p");
  4167.   defsymbol (&Qfile_readable_p, "file-readable-p");
  4168.   defsymbol (&Qfile_symlink_p, "file-symlink-p");
  4169.   defsymbol (&Qfile_writable_p, "file-writable-p");
  4170.   defsymbol (&Qfile_directory_p, "file-directory-p");
  4171.   defsymbol (&Qfile_accessible_directory_p, "file-accessible-directory-p");
  4172.   defsymbol (&Qfile_modes, "file-modes");
  4173.   defsymbol (&Qset_file_modes, "set-file-modes");
  4174.   defsymbol (&Qfile_newer_than_file_p, "file-newer-than-file-p");
  4175.   defsymbol (&Qinsert_file_contents, "insert-file-contents");
  4176.   defsymbol (&Qwrite_region, "write-region");
  4177.   defsymbol (&Qverify_visited_file_modtime, "verify-visited-file-modtime");
  4178.   defsymbol (&Qset_visited_file_modtime, "set-visited-file-modtime");
  4179.   defsymbol (&Qset_buffer_modtime, "set-buffer-modtime");
  4180. #ifdef MSDOS
  4181.   defsymbol (&Qfind_buffer_file_type, "find-buffer-file-type");
  4182. #endif
  4183.   defsymbol (&Qcar_less_than_car, "car-less-than-car"); /* Vomitous! */
  4184.  
  4185.   defsymbol (&Qfile_name_handler_alist, "file-name-handler-alist");
  4186.   defsymbol (&Qauto_save_hook, "auto-save-hook");
  4187.   defsymbol (&Qauto_save_error, "auto-save-error");
  4188.   defsymbol (&Qauto_saving, "auto-saving");
  4189.  
  4190.   deferror (&Qfile_error, "file-error", "File error", 1);
  4191.   deferror (&Qfile_already_exists, "file-already-exists",
  4192.         "File already exists", 4);
  4193.  
  4194.   defsubr (&Sfind_file_name_handler);
  4195.  
  4196.   defsubr (&Sfile_name_directory);
  4197.   defsubr (&Sfile_name_nondirectory);
  4198.   defsubr (&Sunhandled_file_name_directory);
  4199.   defsubr (&Sfile_name_as_directory);
  4200.   defsubr (&Sdirectory_file_name);
  4201.   defsubr (&Smake_temp_name);
  4202.   defsubr (&Sexpand_file_name);
  4203.   defsubr (&Sfile_truename);
  4204.   defsubr (&Ssubstitute_in_file_name);
  4205.   defsubr (&Scopy_file);
  4206.   defsubr (&Smake_directory_internal);
  4207.   defsubr (&Sdelete_directory);
  4208.   defsubr (&Sdelete_file);
  4209.   defsubr (&Srename_file);
  4210.   defsubr (&Sadd_name_to_file);
  4211. #ifdef S_IFLNK
  4212.   defsubr (&Smake_symbolic_link);
  4213. #endif /* S_IFLNK */
  4214. #ifdef VMS
  4215.   defsubr (&Sdefine_logical_name);
  4216. #endif /* VMS */
  4217. #ifdef HPUX_NET
  4218.   defsubr (&Ssysnetunam);
  4219. #endif /* HPUX_NET */
  4220.   defsubr (&Sfile_name_absolute_p);
  4221.   defsubr (&Sfile_exists_p);
  4222.   defsubr (&Sfile_executable_p);
  4223.   defsubr (&Sfile_readable_p);
  4224.   defsubr (&Sfile_writable_p);
  4225.   defsubr (&Sfile_symlink_p);
  4226.   defsubr (&Sfile_directory_p);
  4227.   defsubr (&Sfile_accessible_directory_p);
  4228.   defsubr (&Sfile_modes);
  4229.   defsubr (&Sset_file_modes);
  4230.   defsubr (&Sset_default_file_modes);
  4231.   defsubr (&Sdefault_file_modes);
  4232.   defsubr (&Sunix_sync);
  4233.   defsubr (&Sfile_newer_than_file_p);
  4234.   defsubr (&Sinsert_file_contents_internal);
  4235.   defsubr (&Swrite_region_internal);
  4236.   defsubr (&Scar_less_than_car); /* Vomitous! */
  4237. #if 0
  4238.   defsubr (&Sencrypt_string);
  4239.   defsubr (&Sdecrypt_string);
  4240. #endif
  4241.   defsubr (&Sverify_visited_file_modtime);
  4242.   defsubr (&Sclear_visited_file_modtime);
  4243.   defsubr (&Svisited_file_modtime);
  4244.   defsubr (&Sset_visited_file_modtime);
  4245.   defsubr (&Sset_buffer_modtime);
  4246.   defsubr (&Scompute_buffer_file_truename);
  4247.  
  4248.   defsubr (&Sdo_auto_save);
  4249.   defsubr (&Sset_buffer_auto_saved);
  4250.   defsubr (&Sclear_buffer_auto_save_failure);
  4251.   defsubr (&Srecent_auto_save_p);
  4252. }
  4253.  
  4254. void
  4255. vars_of_fileio (void)
  4256. {
  4257.   DEFVAR_BOOL ("vms-stmlf-recfm", &vms_stmlf_recfm,
  4258.     "*Non-nil means write new files with record format `stmlf'.\n\
  4259. nil means use format `var'.  This variable is meaningful only on VMS.");
  4260.   vms_stmlf_recfm = 0;
  4261.  
  4262.   DEFVAR_LISP ("file-name-handler-alist", &Vfile_name_handler_alist,
  4263.     "*Alist of elements (REGEXP . HANDLER) for file names handled specially.\n\
  4264. If a file name matches REGEXP, then all I/O on that file is done by calling\n\
  4265. HANDLER.\n\
  4266. \n\
  4267. The first argument given to HANDLER is the name of the I/O primitive\n\
  4268. to be handled; the remaining arguments are the arguments that were\n\
  4269. passed to that primitive.  For example, if you do\n\
  4270.     (file-exists-p FILENAME)\n\
  4271. and FILENAME is handled by HANDLER, then HANDLER is called like this:\n\
  4272.     (funcall HANDLER 'file-exists-p FILENAME)\n\
  4273. The function `find-file-name-handler' checks this list for a handler\n\
  4274. for its argument.");
  4275.   Vfile_name_handler_alist = Qnil;
  4276.  
  4277.   DEFVAR_LISP ("after-insert-file-functions", &Vafter_insert_file_functions,
  4278.     "A list of functions to be called at the end of `insert-file-contents'.\n\
  4279. Each is passed one argument, the number of bytes inserted.  It should return\n\
  4280. the new byte count, and leave point the same.  If `insert-file-contents' is\n\
  4281. intercepted by a handler from `file-name-handler-alist', that handler is\n\
  4282. responsible for calling the after-insert-file-functions if appropriate.");
  4283.   Vafter_insert_file_functions = Qnil;
  4284.  
  4285.   DEFVAR_LISP ("write-region-annotate-functions",
  4286.            &Vwrite_region_annotate_functions,
  4287.     "A list of functions to be called at the start of `write-region'.\n\
  4288. Each is passed two arguments, START and END as for `write-region'.\n\
  4289. It should return a list of pairs (POSITION . STRING) of strings to be\n\
  4290. effectively inserted at the specified positions of the file being written\n\
  4291. \(1 means to insert before the first byte written).  The POSITIONs must be\n\
  4292. sorted into increasing order.  If there are several functions in the list,\n\
  4293. the several lists are merged destructively.");
  4294.   Vwrite_region_annotate_functions = Qnil;
  4295.  
  4296.   DEFVAR_LISP ("write-region-annotations-so-far",
  4297.            &Vwrite_region_annotations_so_far,
  4298.     "When an annotation function is called, this holds the previous annotations.\n\
  4299. These are the annotations made by other annotation functions\n\
  4300. that were already called.  See also `write-region-annotate-functions'.");
  4301.   Vwrite_region_annotations_so_far = Qnil;
  4302.  
  4303.   DEFVAR_LISP ("inhibit-file-name-handlers", &Vinhibit_file_name_handlers,
  4304.     "A list of file name handlers that temporarily should not be used.\n\
  4305. This applies only to the operation `inhibit-file-name-operation'.");
  4306.   Vinhibit_file_name_handlers = Qnil;
  4307.  
  4308.   DEFVAR_LISP ("inhibit-file-name-operation", &Vinhibit_file_name_operation,
  4309.     "The operation for which `inhibit-file-name-handlers' is applicable.");
  4310.   Vinhibit_file_name_operation = Qnil;
  4311.  
  4312.   DEFVAR_LISP ("auto-save-list-file-name", &Vauto_save_list_file_name,
  4313.     "File name in which we write a list of all auto save file names.");
  4314.   Vauto_save_list_file_name = Qnil;
  4315. }
  4316.